Flask-babel:每位用户翻译

dar*_*nto 2 python flask

如何使用Flask-Babel翻译每个用户使用特定语言的页面?我可以翻译所有用户页面设置:"app.config ['BABEL_DEFAULT_LOCALE'] ='en'".我该如何为每位用户翻译?

tbi*_*icr 5

请参阅文档: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'])
Run Code Online (Sandbox Code Playgroud)

您可以从用户在数据库中,从URL,域或子域,从用户请求标头获取区域设置.您可以拥有自己的区域设置检测方法,但需要返回区域设置babel.localeselector.如果babel.localeselector无法获取语言环境,则使用默认语言环境BABEL_DEFAULT_LOCALE.

当您获得正确的区域设置时,还需要创建翻译.po以及.mo每个受支持的区域设置.不要忘记每个翻译的字符串必须标记为翻译.