Flask-babel:每位用户翻译

时间:2013-10-11 08:04:25

标签: python flask

如何使用Flask-Babel翻译每位用户使用特定语言的网页?我可以翻译所有用户页面设置:“app.config ['BABEL_DEFAULT_LOCALE'] ='en'”。我如何根据用户进行翻译?

1 个答案:

答案 0 :(得分: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'])

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

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

相关问题