Search code examples
pythonflaskmultilingualpython-babelflask-babel

Flask-Babel localeselector is not being called


Flask-babel doesn't call its localeselector even once. I'm using app factory to init my app. The translations folder is within my app, It was created by babel, according to the docs. I've also tried moving the translations dir to the folder containing the run.py, which calls the factory, but to no effect.

from flask import Flask, session, request
from myapp.text_fields import next_month
from myapp.config import Config
from flask_babel import Babel

babel = Babel()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(Config)

    babel.init_app(app)

    from myapp.views import user
    from myapp.errors import errors

    app.register_blueprint(user)
    app.register_blueprint(errors)

    @babel.localeselector
    def get_locale():
        try:
            language = session['language']
        except KeyError:
            language = None
        if language is not None:
            return language
        return request.accept_languages.best_match(app.config['LANGUAGES'])

    @app.context_processor
    def inject_conf_var():
        return dict(
            MONTH=next_month(),
            AVAILABLE_LANGUAGES=app.config['LANGUAGES'],
            CURRENT_LANGUAGE=session.get('language',
                                         request.accept_languages.best_match(app.config['LANGUAGES'])))

    return app

Here's the config part concerning babel:

BABEL_DEFAULT_LOCALE = 'pl'
LANGUAGES = ['pl', 'ua', 'ru', 'en']

So far I've complied only EN, tried to change the default, but it doens't do anything either. Seems like babel is not able to locate the translations folder, I'm not sure how to fix this.


Solution

  • Solved it, turned out I had to move localeselector out of the factory. Since most of my text fields are generated on the service side rather than forntend, I also had to use lazy_text on all of them, as they are called by endpoints rather than defined within them.