babel.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # ********************************************************************************
  4. # Copyright © 2018 jianglin
  5. # File Name: babel.py
  6. # Author: jianglin
  7. # Email: xiyang0807@gmail.com
  8. # Created: 2018-02-11 14:52:25 (CST)
  9. # Last Update: 星期日 2018-02-11 15:31:25 (CST)
  10. # By:
  11. # Description:
  12. # ********************************************************************************
  13. from flask import request, g, current_app
  14. from flask_babelex import Babel, Domain
  15. import os
  16. translations = os.path.abspath(
  17. os.path.join(
  18. os.path.dirname(__file__), os.pardir, os.pardir, 'translations'))
  19. domain = Domain(translations)
  20. babel = Babel(default_domain=domain)
  21. @babel.localeselector
  22. def locale():
  23. user = getattr(g, 'user', None)
  24. if user is not None:
  25. if request.path.startswith('/admin'):
  26. return 'zh_Hans_CN'
  27. if g.user.is_authenticated:
  28. return user.setting.locale or 'zh'
  29. return request.accept_languages.best_match(current_app.config['LANGUAGES']
  30. .keys())
  31. @babel.timezoneselector
  32. def timezone():
  33. user = getattr(g, 'user', None)
  34. if user is not None:
  35. if g.user.is_authenticated:
  36. return user.setting.timezone or 'UTC'
  37. return 'UTC'
  38. def init_app(app):
  39. babel.init_app(app)