修改Flask-Babel非请求上下文下的语言环境以用于预定任务

2024-05-03 22:16:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我每小时运行一个可以向用户发送电子邮件的作业。发送电子邮件时,需要使用用户设置的语言(保存在数据库中)。 我无法找到在请求上下文之外设置其他区域设置的方法。在

我想做的是:

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

Tags: 方法用户in语言数据库区域fortask
3条回答

@ZeWaren的回答很好,如果你使用的是Flask Babel,但是如果你使用的是Flask BabelEx,就没有force_locale方法。在

这是烧瓶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对象的根路径是'主应用程序'这会让巴贝尔在'app.main.翻译“当他们在的时候”应用程序翻译'. 它会悄悄地回到NullTranslations,也就是说,不翻译。在

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

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通过调用@巴别尔本地选择器. 我的localeselector如下所示:

^{pr2}$

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

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

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

它的docstring是这样说的:

^{pr2}$

相关问题 更多 >