manager.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import os
  2. from flask import has_request_context, request, session
  3. from flask_appbuilder.babel.views import LocaleView
  4. from flask_appbuilder.basemanager import BaseManager
  5. from flask_babel import Babel
  6. class BabelManager(BaseManager):
  7. babel = None
  8. locale_view = None
  9. def __init__(self, appbuilder):
  10. super(BabelManager, self).__init__(appbuilder)
  11. app = appbuilder.get_app
  12. app.config.setdefault("BABEL_DEFAULT_LOCALE", "en")
  13. if not app.config.get("LANGUAGES"):
  14. app.config["LANGUAGES"] = {"en": {"flag": "us", "name": "English"}}
  15. appbuilder_parent_dir = os.path.join(
  16. os.path.dirname(os.path.abspath(__file__)), os.pardir
  17. )
  18. appbuilder_translations_path = os.path.join(
  19. appbuilder_parent_dir, "translations"
  20. )
  21. if "BABEL_TRANSLATION_DIRECTORIES" in app.config:
  22. current_translation_directories = app.config.get(
  23. "BABEL_TRANSLATION_DIRECTORIES"
  24. )
  25. translations_path = (
  26. appbuilder_translations_path + ";" + current_translation_directories
  27. )
  28. else:
  29. translations_path = appbuilder_translations_path + ";translations"
  30. app.config["BABEL_TRANSLATION_DIRECTORIES"] = translations_path
  31. self.babel = Babel(app)
  32. self.babel.locale_selector_func = self.get_locale
  33. def register_views(self):
  34. self.locale_view = LocaleView()
  35. self.appbuilder.add_view_no_menu(self.locale_view)
  36. @property
  37. def babel_default_locale(self):
  38. return self.appbuilder.get_app.config["BABEL_DEFAULT_LOCALE"]
  39. @property
  40. def languages(self):
  41. return self.appbuilder.get_app.config["LANGUAGES"]
  42. def get_locale(self):
  43. if has_request_context():
  44. # locale selector for API searches for request args
  45. for arg, value in request.args.items():
  46. if arg == "_l_":
  47. if value in self.languages:
  48. return value
  49. else:
  50. return self.babel_default_locale
  51. locale = session.get("locale")
  52. if locale:
  53. return locale
  54. session["locale"] = self.babel_default_locale
  55. return session["locale"]