在计划任务的请求上下文之外更改Flask-Babel语言环境

时间:2014-03-19 10:09:07

标签: python flask locale babel

我每小时都有一份工作,可以向用户发送电子邮件。发送电子邮件时,需要使用用户设置的语言(保存在数据库中)。 我无法找到在请求上下文之外设置不同语言环境的方法。

以下是我想做的事情:

def scheduled_task():
  for user in users:
    set_locale(user.locale)
    print lazy_gettext(u"This text should be in your language")

3 个答案:

答案 0 :(得分:11)

您还可以使用包force_locale中的方法flask.ext.babel

from flask.ext.babel import force_locale as babel_force_locale
english_version = _('Translate me')
with babel_force_locale('fr'):
    french_version = _("Translate me")

这是其文档字符串所说的内容:

"""Temporarily overrides the currently selected locale.

Sometimes it is useful to switch the current locale to different one, do
some tasks and then revert back to the original one. For example, if the
user uses German on the web site, but you want to send them an email in
English, you can use this function as a context manager::

    with force_locale('en_US'):
        send_email(gettext('Hello!'), ...)

:param locale: The locale to temporary switch to (ex: 'en_US').
"""

答案 1 :(得分:3)

一种方法是设置虚拟请求上下文:

with app.request_context({'wsgi.url_scheme': "", 'SERVER_PORT': "", 'SERVER_NAME': "", 'REQUEST_METHOD': ""}):
    from flask import g
    from flask_babel import refresh
    # set your user class with locale info to Flask proxy
    g.user = user
    # refreshing the locale and timezeone
    refresh()
    print lazy_gettext(u"This text should be in your language")

Flask-Babel通过调用@ babel.localeselector获取其语言环境设置。 我的localeselector看起来像这样:

@babel.localeselector
def get_locale():
    user = getattr(g, 'user', None)
    if user is not None and user.locale:
        return user.locale
    return en_GB   

现在,每次更改g.user时,都应调用refresh()来刷新Flask-Babel语言环境设置

答案 2 :(得分:2)

如果您使用的是Flask-Babel,那么@ZeWaren的回答非常好,但如果您使用的是Flask-BabelEx,则没有force_locale方法。

这是Flask-BabelEx的解决方案:

app = Flask(__name__.split('.')[0])   #  See http://flask.pocoo.org/docs/0.11/api/#application-object

with app.test_request_context() as ctx:
    ctx.babel_locale = Locale.parse(lang)
    print _("Hello world")

注意如果您使用蓝图,.split()很重要。我挣扎了几个小时,因为app对象是使用root_path创建的'app.main',这会让Babel在'app.main.translations'中查找翻译文件。翻译。它会默默地回归NullTranslations,即不翻译。