我每小时运行一份工作,可以发送电子邮件给用户。当电子邮件被发送时,它需要使用用户设置的语言(保存在db中)。我无法找到在请求上下文之外设置不同区域设置的方法。
以下是我想做的事:
def scheduled_task():
for user in users:
set_locale(user.locale)
print lazy_gettext(u"This text should be in your language")发布于 2016-03-11 11:02:41
一种方法是设置虚拟请求上下文:
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")烧瓶-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 现在,每次更改g.user时,都应该调用refresh()来刷新Flask地区设置。
发布于 2016-08-10 17:21:31
您还可以使用包flask.ext.babel中的方法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")下面是它的docstring的意思:
"""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').
"""发布于 2017-09-04 11:55:38
@ZeWaren的回答很棒,如果你使用的是水瓶-Babel,但是如果你使用的是烧瓶-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‘的root_path创建的,这会使Babel在’app.transports‘中查找'app.main.translations’中的翻译文件。它会悄悄地退回到NullTranslations,即不翻译。
https://stackoverflow.com/questions/22502370
复制相似问题