【问题标题】:Change Flask-Babel locale outside of request context for scheduled tasks在计划任务的请求上下文之外更改 Flask-Babel 语言环境
【发布时间】:2014-04-25 11:48:15
【问题描述】:

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

这是我想做的:

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

【问题讨论】:

    标签: python flask locale python-babel flask-babel


    【解决方案1】:

    您也可以使用包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').
    """
    

    【讨论】:

    • 完美! ——你救了我。
    【解决方案2】:

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

    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 通过调用@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-Babel 语言环境设置

    【讨论】:

      【解决方案3】:

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

      这是 Flask-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.main.translations' 中查找翻译文件,而它们在 'app.translations' 中.它会默默地退回到NullTranslations,即不翻译。

      【讨论】:

        【解决方案4】:

        假设 Flask-Babel 使用请求上下文范围的区域设置,您可以尝试使用临时请求上下文运行您的代码:

        with app.request_context(environ):
            do_something_with(request)
        

        http://flask.pocoo.org/docs/0.10/api/#flask.Flask.request_context

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-03
          • 2015-09-06
          • 1970-01-01
          相关资源
          最近更新 更多