Flask-Babel: get_locale() seems to be not working

2.8k views Asked by At

I'm configuring flask-babel to translate an html page from English as base language to Portuguese as translated language. However, no changes at get_locale() reflected in a different language.

These are my current relevant codes:

app.py:

from flask import Flask, render_template
from flask_babel import Babel
from flask_babel import gettext as _

app = Flask(__name__)

app.config['BABEL_DEFAULT_LOCALE'] = 'pt'

babel = Babel(app)
babel.init_app(app)

def get_locale():
    return 'en'
    
@app.route('/')
def index():
        return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True)

html:

<!DOCTYPE html>
<html lang="en">
    <body>
        <h1>{{ _('Word') }}</h1>
    </body>
</html>

Switching manually app.config['BABEL_DEFAULT_LOCALE'] = 'pt' seems to show equivalent translated word as written in '.po' file and then compiled, and switching ['BABEL_DEFAULT_LOCALE'] to 'en' and get_locale() to 'pt' seems to show the untranslated word again. In other words, I think my 'messages.mo' file is working as intended. It's as if the get_locale() function is getting ignored.

I'm using flask 2.2.2 and flask-babel 3.0.0, thus, I didn't insert @babel.localeselector as it seems it's not needed (and returns unrecognized decorator when inserted).

Thanks in advance

----- ANSWER -----

Using babel.init_app(app, locale_selector=get_locale) didn't work for the first few times, until I wrote my code in the following order: babel initialization, then get_locale() function, then init_app.

from flask import Flask, render_template
from flask_babel import Babel
from flask_babel import gettext as _

app = Flask(__name__)

app.config['BABEL_DEFAULT_LOCALE'] = 'en'

babel = Babel(app)

def get_locale():
  return 'en'

babel.init_app(app, locale_selector=get_locale)

  
@app.route('/')
def index():
      return render_template('index.html')

if __name__ == "__main__":
  app.run(debug=True)

2

There are 2 answers

0
rzlvmp On BEST ANSWER

Did you check documentation?

You have to set locale_selector to be able use own function:

...
def get_locale():
    return 'en'

babel = Babel(app)
babel.init_app(app, locale_selector=get_locale)
...
0
InD On

The accepted answer is correct: It's written in the documentation. But the example can be even simpler. You can specifiy the local selector when creating the Babel object:

...

def get_locale():
    return 'en'

babel = Babel(app, locale_selector=get_locale)

...

init_app() will be called automatically with the provided local_selector in the __init__() function when app is not None.