首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在计划任务的请求上下文之外更改Flask-Babel区域设置

在计划任务的请求上下文之外更改Flask-Babel区域设置
EN

Stack Overflow用户
提问于 2014-03-19 10:09:06
回答 4查看 4.2K关注 0票数 6

我每小时运行一份工作,可以发送电子邮件给用户。当电子邮件被发送时,它需要使用用户设置的语言(保存在db中)。我无法找到在请求上下文之外设置不同区域设置的方法。

以下是我想做的事:

代码语言:javascript
复制
def scheduled_task():
  for user in users:
    set_locale(user.locale)
    print lazy_gettext(u"This text should be in your language")
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-03-11 11:02:41

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

代码语言:javascript
复制
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获得它的地区设置。我的地方选民看起来是这样的:

代码语言:javascript
复制
@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地区设置。

票数 5
EN

Stack Overflow用户

发布于 2016-08-10 17:21:31

您还可以使用包flask.ext.babel中的方法flask.ext.babel

代码语言:javascript
复制
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的意思:

代码语言:javascript
复制
"""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').
"""
票数 15
EN

Stack Overflow用户

发布于 2017-09-04 11:55:38

@ZeWaren的回答很棒,如果你使用的是水瓶-Babel,但是如果你使用的是烧瓶-BabelEx,就没有force_locale方法了。

这是一个解决方案的瓶-BabelEx:

代码语言:javascript
复制
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,即不翻译。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22502370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档