python-babel / flask-babel

i18n and l10n support for Flask based on Babel and pytz
https://python-babel.github.io/flask-babel/
Other
432 stars 159 forks source link

Why babel load translations every request? #154

Closed WokoLiu closed 3 years ago

WokoLiu commented 5 years ago

When I use flask_babel.gettext function, I found that it would walk all the BABEL_TRANSLATION_DIRECTORIES to find and load locate&translations every request.

Is it necessary? Why we do this? Maybe we can load all the .mo file before every real request?

Or do I use it wrong?

Here is my localeselector.

from flask import request

@babel.localeselector
    def get_locale():
        return request.accept_languages.best

Please tell me I'm wrong... Thanks

ghost commented 5 years ago

I've been tracking through the code and came to the same conclusion (I doubted myself as it's seems pretty odd). It's this function:

def _get_current_context():
    if has_request_context():
        return request

    if current_app:
        return current_app

which could be optimised. Unfortunately it's a global function, i.e. not in the Babel class, so is hard to override :-(

jace commented 5 years ago

The forked Flask-BabelEx project cites this as the reason for it to exist. Unfortunately it doesn't seem as well maintained.

TkTech commented 3 years ago

Resolved in v2.0.0, pending release.

mcejp commented 3 years ago

This is great in production, but is there a way to get the previous behavior in debug mode, for example?