Flask-Babel

4.0.0 · active · verified Mon Apr 06

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Flask-Babel with a Flask application, set up default locales and available languages, and define a `localeselector` function to determine the user's preferred language. It also includes basic usage of `gettext` for string internationalization and outlines the necessary `pybabel` commands for translation file management.

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)

view raw JSON →