Flask-Babel
Flask-Babel is an extension for the Flask micro-framework that adds internationalization (i18n) and localization (l10n) support to Flask applications. It provides built-in features for date and time formatting with timezone support, as well as a friendly interface for gettext translations. The library is actively maintained, with the current version being 4.0.0, and has a consistent release cadence.
Warnings
- breaking Version 4.0.0 dropped support for Python 3.7. Applications running on Python 3.7 or older must upgrade their Python environment or use an older Flask-Babel version.
- breaking Version 3.1.0 requires Babel 12.2 or greater. Ensure your `babel` package is updated to avoid compatibility issues, particularly with localized time formatting.
- breaking Version 3.0.0 made several significant breaking changes, including dropping support for Python 3.5 and 3.6, and requiring Jinja version 3 or greater.
- breaking In version 3.0.0, the internal attribute `Babel._date_formats` was removed. Users should now use the public `Babel.date_formats` attribute instead.
- gotcha Older Flask extensions used the `flask.ext` namespace (e.g., `flask.ext.babel`). This pattern is deprecated. Always import directly from `flask_babel`.
- gotcha Flask-Babel defaults the `BABEL_DEFAULT_TIMEZONE` to 'UTC'. It is crucial that your application internally uses 'UTC' for date and time storage to prevent unexpected behavior with user-facing localized dates.
Install
-
pip install Flask-Babel
Imports
- Babel
from flask_babel import Babel
- gettext
from flask_babel import gettext from flask_babel import _
Quickstart
from flask import Flask, render_template, request
from flask_babel import Babel, gettext
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
app.config['LANGUAGES'] = {'en': 'English', 'de': 'Deutsch'}
babel = Babel(app)
@babel.localeselector
def get_locale():
# Try to guess the language from the user's browser accept header
# or use a default/configured locale.
return request.accept_languages.best_match(list(app.config['LANGUAGES'].keys()))
@app.route('/')
def index():
return f"<h1>{gettext('Hello, World!')}</h1>"
# To run this example, you would also need a `messages.po` file and compile it.
# 1. Create a `babel.cfg` file:
# [python: **.py]
# [jinja2: **/templates/**.html]
# 2. Extract messages:
# pybabel extract -F babel.cfg -o messages.pot .
# 3. Initialize translation for a language (e.g., German):
# pybabel init -i messages.pot -d translations -l de
# 4. Translate strings in `translations/de/LC_MESSAGES/messages.po`
# 5. Compile translations:
# pybabel compile -d translations
if __name__ == '__main__':
app.run(debug=True)