我每小时运行一个可以向用户发送电子邮件的作业。发送电子邮件时,需要使用用户设置的语言(保存在数据库中)。 我想不出在请求上下文之外设置不同语言环境的方法。
这是我想做的:
def scheduled_task():
for user in users:
set_locale(user.locale)
print lazy_gettext(u"This text should be in your language")
最佳答案
您还可以使用包 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")
这是它的文档字符串:
"""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').
"""
关于python - 在计划任务的请求上下文之外更改 Flask-Babel 语言环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22502370/