mickael mickael - 10 months ago 92
Python Question

Change Flask-Babel locale outside of request context for scheduled tasks

I run a job every hour that can send an email to users. When the email is sent, it needs to be in the language set by the user (saved in the db).
I can't figure out a way to set a different locale outside of a request context.

Here is what I would like to do:

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


One way to do it is to set up 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
    print lazy_gettext(u"This text should be in your language")

Flask-Babel gets its locale settings by calling @babel.localeselector. My localeselector looks something like this:

def get_locale():
    user = getattr(g, 'user', None)
    if user is not None and user.locale:
    return user.locale
return en_GB

Now every time you change your g.user you should call refresh() to refresh Flask-Babel locale settings