Flask-Security, dynamic url prefix for multilingual page (with Flask-Babelex)

328 Views Asked by At

I am adding Flask-Babelex to my website. I register blueprints with url_prefix as such:

from app.main import bp as main_bp
    app.register_blueprint(main_bp, url_prefix="/<lang_code>")

I set up babel.localeselector as follows:

@babel.localeselector
    def get_locale():
        if not g.get('lang_code', None):
            g.lang_code = request.accept_languages.best_match(app.config['LANGUAGES'])
        return g.lang_code

Then in the routes.py file of the respective blueprint I add:

@bp.url_defaults
def add_language_code(endpoint, values):
    values.setdefault('lang_code', g.lang_code)


@bp.url_value_preprocessor
def pull_lang_code(endpoint, values):
    g.lang_code = values.pop('lang_code')

Basically, I am following what's been done here, and it's been working pretty well. What I cannot seem to be able to achieve, is force Flask-Security-Too to work with this variable url_prefix.

If I do not change anything in flask-security configuration, and access localhost:5000/change_password it throws "UnknownLocaleError: unknown locale 'change_password'" at me, which is understandable. If I access localhost:5000/pl/change_password, I get "AttributeError: '_AppCtxGlobals' object has no attribute 'lang_code'".

Now I can set up the SECURITY_URL_PREFIX config parameter to "/<lang_code>", but then I get "AttributeError: '_AppCtxGlobals' object has no attribute 'lang_code'" as well.

How can I pass the information what lang_code is to Flask-Security?

Edit:
Config:

SECURITY_PASSWORD_SALT = os.environ.get("SECURITY_PASSWORD_SALT")
SECURITY_REGISTERABLE = True
SECURITY_CONFIRMABLE = True
SECURITY_CONFIRM_REGISTER_FORM = ExtendedRegisterForm
SECURITY_TRACKABLE = True
SECURITY_CHANGEABLE = True
SECURITY_RECOVERABLE = True
SECURITY_CHANGE_URL = "/change_password"
SECURITY_POST_LOGIN_VIEW = "/dashboard"
SECURITY_POST_CONFIRM_VIEW = "/welcome"

Versions:

  • Flask-BabelEx==0.9.4
  • Flask-Security-Too==3.4.5
0

There are 0 best solutions below