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

标签 python flask locale python-babel flask-babel

我每小时运行一个可以向用户发送电子邮件的作业。发送电子邮件时,需要使用用户设置的语言(保存在数据库中)。 我想不出在请求上下文之外设置不同语言环境的方法。

这是我想做的:

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/

相关文章:

python - 在OpenCV的HoughCircles方法中确定参数

Python re.findall() 获取所有匹配的组

python - 带有 login_required 的单元测试 flask 应用程序

java - 如何使用区域设置获取特定国家/地区的货币符号?

java - 有没有办法强制异常消息为 Java 1.7 的英语

python - 将网格从中心坐标重新采样到外部(即角)坐标

python - 从 Python 中捕获音频

python - 如何在目录中的文件上运行gunicorn?

html - 在处理 Jinja 模板时,如何将图像 float 到容器外?

bash - 无法打印句点千位分隔符