pythonflaskflask-appbuilderpython-babel

get current language in flask appbuilder


I have a simple app wrote with Flask Appbuilder, the view.py is as follows. It is part of exmaple in http://flask-appbuilder.readthedocs.io/en/latest/views.html with a little change in method1 where I replaced return 'Hello' with a function that I wish to find.

We can change the language in app (en,fr,ru,...) and translate it. Is there a function to get the current language? (Current_Language()).

from flask_appbuilder import AppBuilder, BaseView, expose, has_access, ModelView
from app import appbuilder, db
from flask import render_template, g
from flask_babel import Babel
from flask_babel import lazy_gettext as _
from flask_appbuilder.models.sqla.interface import SQLAInterface

class MyView(BaseView):    
  default_view = 'method1'    
  @expose('/method1/')
  @has_access
  def method1(self):
    return Current_Language()

appbuilder.add_view(MyView, "Method1", category='My View')

Solution

  • The appbuilder instance has a bm attribute, which is an instance of the BabelManager class.

    This class has a get_locale method that returns the current language your app is using.

    class MyView(BaseView):    
        default_view = 'method1'    
        @expose('/method1/')
        @has_access
        def method1(self):
            return appbuilder.bm.get_locale()
    

    You can check the code for the BabelManager class on the project repository.