Change Flask-Babel locale out of context for query for scheduled tasks

I do work every hour to send emails to users. When the email is sent, it must be in the language specified by the user (stored in db). I cannot find a way to set a different locale outside the request context.

Here is what I would like to do:

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

One way to do this is to create a dummy request context:

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 gets its language settings by calling @ babel.localeselector. My localeselector looks something like this:

@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

+2

force_locale 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').
"""
+8

@ZeWaren , Flask-Babel, 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 root_path "app.main", Babel "app.main.translations", "app.translations", NullTranslations .

+1

, Flask-Babel , :

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

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

0
source

Source: https://habr.com/ru/post/1532452/


All Articles