How to use flask babel gettext in celery?

193 Views Asked by At

I have a flask-celery setup with flask babel translating my texts. I can't translate in celery tasks. I believe this is because it doesn't know the current language (I'm not it could even if it did) and this is because celery doesn't have access to the request context (from what i understood)...

What would be the solution to be able to translate?

1

There are 1 best solutions below

1
On

You rightly pointed out that issue that is celery doesn't have access to request context, which means flask_babelex.get_locale returns None. You can use force_locale context manager available in Flask-Babel which provides dummy request context.

from contextlib import contextmanager
from flask import current_app
from babel import Locale

from ..config import SERVER_NAME, PREFERRED_URL_SCHEME


@contextmanager
def force_locale(locale=None):
    if not locale:
        yield
            return

    env = {
        'wsgi.url_scheme': PREFERRED_URL_SCHEME,
        'SERVER_NAME': SERVER_NAME,
        'SERVER_PORT': '',
        'REQUEST_METHOD': ''
    }
    with current_app.request_context(env) as ctx:
        ctx.babel_locale = Locale.parse(locale)
        yield

Sample Celery Task

@celery.task()
def some_task(user_id):
    user = User.objects.get(id=user_id)
    with force_locale(user.locale):
        ...gettext('TranslationKey')...