如何使用 Flask-Babel 为每个用户翻译特定语言的页面?我可以翻译所有用户页面设置:“app.config['BABEL_DEFAULT_LOCALE'] = 'en'”。如何为每个用户翻译它?
最佳答案
参见文档:http://pythonhosted.org/Flask-Babel/#configuration :
from flask import g, request
@babel.localeselector
def get_locale():
# if a user is logged in, use the locale from the user settings
user = getattr(g, 'user', None)
if user is not None:
return user.locale
# otherwise try to guess the language from the user accept
# header the browser transmits. We support de/fr/en in this
# example. The best match wins.
return request.accept_languages.best_match(['de', 'fr', 'en'])
您可以从数据库中的用户、url、域或子域、用户请求 header 获取区域设置。您可以拥有自己的语言环境检测方法,但需要使用 babel.localeselector 返回语言环境。如果 babel.localeselector
无法获取区域设置,则会使用 BABEL_DEFAULT_LOCALE
中的默认区域设置。
当您获得正确的语言环境时,您还需要为每个支持的语言环境创建翻译 .po
和 .mo
。不要忘记每个翻译的字符串必须标记为翻译。
关于python - Flask-babel : translation per user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19313218/