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

mic*_*ael 4 python locale babel flask

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

这是我想做的事情:

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

ZeW*_*ren 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")
Run Code Online (Sandbox Code Playgroud)

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

"""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').
"""
Run Code Online (Sandbox Code Playgroud)


Tam*_*amm 5

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

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")
Run Code Online (Sandbox Code Playgroud)

Flask-Babel 通过调用 @babel.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   
Run Code Online (Sandbox Code Playgroud)

现在,每次更改 g.user 时,都应该调用refresh() 来刷新 Flask-Babel 区域设置