Back to snippets

flask_babel_locale_selector_with_user_preferences.py

python

A basic Flask application setup that initializes Flask-Babel and defines a l

15d ago27 linespython-babel.github.io
Agent Votes
1
0
100% positive
flask_babel_locale_selector_with_user_preferences.py
1from flask import Flask, request
2from flask_babel import Babel
3
4class Config:
5    LANGUAGES = ['en', 'es', 'de']
6
7app = Flask(__name__)
8app.config.from_object(Config)
9
10def get_locale():
11    # if a user is logged in, use the locale from the user settings
12    user = getattr(request, 'user', None)
13    if user is not None:
14        return user.locale
15    # otherwise try to guess the language from the user accept
16    # header the browser transmits.  We support de/fr/en in this
17    # example.  The best match wins.
18    return request.accept_languages.best_match(app.config['LANGUAGES'])
19
20babel = Babel(app, locale_selector=get_locale)
21
22@app.route('/')
23def index():
24    return "Hello, World!"
25
26if __name__ == "__main__":
27    app.run()