Registry / web-framework / flask-babel

flask-babel

JSON →
library4.0.0pypypi✓ verified 26d ago

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.

pip install Flask-Babel
INSTALL
IMPORT
SIG · FLASK-BABEL
F
flask-babel
web-frameworkpythonv4.0.0
Install
3.0s avg
Import
530ms
Disk
57MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.0.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.534s · 58.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.0s · import 0.526s · 59MB
57MB installed
● package 57MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Babel
from flask_babel import Babel
from flask.ext.babel import Babel
The `flask.ext` prefix was deprecated in Flask for extensions; direct import from `flask_babel` is correct since Flask 0.8.
gettext
from flask_babel import gettext from flask_babel import _
Both `gettext` and `_` are commonly used aliases for marking translatable strings.

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)
Debug
Known issues
breakingVersion 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.
fix
Upgrade Python to 3.8 or newer. Alternatively, pin `Flask-Babel<4.0.0`.
affects: 4.0.0+
breakingVersion 3.1.0 requires Babel 12.2 or greater. Ensure your `babel` package is updated to avoid compatibility issues, particularly with localized time formatting.
fix
Update `Babel` to version 12.2 or higher (`pip install -U Babel`).
affects: 3.1.0+
breakingVersion 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.
fix
Upgrade Python to 3.7+ (preferably 3.8+ for v4.0.0) and Jinja2 to version 3 or greater (`pip install -U Jinja2`).
affects: 3.0.0+
breakingIn version 3.0.0, the internal attribute `Babel._date_formats` was removed. Users should now use the public `Babel.date_formats` attribute instead.
fix
Replace any usage of `Babel._date_formats` with `Babel.date_formats`.
affects: 3.0.0+
gotchaOlder Flask extensions used the `flask.ext` namespace (e.g., `flask.ext.babel`). This pattern is deprecated. Always import directly from `flask_babel`.
fix
Update import statements from `from flask.ext.babel import ...` to `from flask_babel import ...`.
affects: <1.0.0 (old codebases)
gotchaFlask-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.
fix
Ensure all date and time storage and manipulation within your application consistently uses UTC. Convert to local timezones only at the presentation layer using Flask-Babel's formatting functions.
affects: All versions
breakingIn Flask-Babel 2.0.0, the `localeselector` and `timezoneselector` decorators were moved from direct application on the `Babel` instance (e.g., `@babel.localeselector`) to a separate `Babel.app` proxy object (e.g., `@babel.app.localeselector`) after `init_app` is called. For newer Flask-Babel versions, `get_locale` and `get_timezone` can also be imported directly.
fix
Replace `@babel.localeselector` with `@babel.app.localeselector` (and similarly for `timezoneselector`) ensuring `babel.init_app(app)` has been called. Alternatively, import and use `get_locale` or `get_timezone` directly from `flask_babel`.
affects: 2.0.0+
Errors
Common errors & fixes
AttributeError: 'Babel' object has no attribute 'localeselector'
In Flask-Babel versions 3.x and later (including 4.0.0), the `@babel.localeselector` decorator was removed. The locale selection function must now be provided directly during the `Babel` object's initialization or via its `init_app` method.
fix
Pass the locale selector function as the `locale_selector` argument to the `Babel` constructor or the `init_app` method. 
```python
from flask import Flask, request
from flask_babel import Babel

app = Flask(__name__)

def get_locale():
    return request.accept_languages.best_match(['en', 'de', 'fr'])

babel = Babel(app, locale_selector=get_locale)
# or if initializing later: babel.init_app(app, locale_selector=get_locale)
```
ImportError: No module named flask_babel
This error typically occurs when the `Flask-Babel` package is not installed in the active Python environment, or when there's an attempt to import the underlying `babel` library directly instead of `flask_babel`.
fix
Ensure `Flask-Babel` is correctly installed in your current Python environment:
```bash
pip install Flask-Babel
```
And make sure to import from `flask_babel`:
```python
from flask_babel import Babel, gettext
```
Translations not appearing / always defaulting to English
This issue can arise from several factors, including incorrect configuration of `BABEL_TRANSLATION_DIRECTORIES`, `pybabel` commands not correctly extracting, initializing, or compiling translation files (`.pot`, `.po`, `.mo`), an improperly defined or uncalled locale selector function, or case sensitivity problems with locale directory names (e.g., 'en' vs. 'EN') on certain operating systems.
fix
1. Verify your `BABEL_TRANSLATION_DIRECTORIES` configuration in `app.config` points to the correct absolute or relative path of your `translations` folder. 
2. Ensure you've run the `pybabel` commands in the correct order: `pybabel extract`, `pybabel init`, and `pybabel compile`. 
3. Check that your `locale_selector` function (passed to `Babel(locale_selector=...)` or `init_app(locale_selector=...)`) is returning the desired locale string. 
4. Confirm that your translation directories (e.g., `translations/fr/LC_MESSAGES/messages.mo`) match the exact case of the locale codes your application expects, especially on Linux-based deployments. 
5. For strings outside the request context or in forms, consider using `lazy_gettext`.
ValueError: Flask-Babel or Flask-BabelEx is installed but not initialized
This error indicates that the `Babel` extension object has been created but has not been associated with a Flask application instance, either by passing the app to its constructor or by calling `babel.init_app(app)`.
fix
Initialize the `Babel` object by passing your Flask application instance to its constructor or by using the `init_app` method:
```python
from flask import Flask
from flask_babel import Babel

app = Flask(__name__)
babel = Babel(app)  # Pass the app instance directly

# Or, if configuring later:
# babel = Babel()
# babel.init_app(app)
```
Upgrade
Version history
4.0.0latest on PyPI · released Oct 2, 2023
Audit
Dependencies
pythonrequiredRequires Python 3.8 or newer for version 4.0.0.
babelrequiredCore library for i18n/l10n; Flask-Babel v3.1.0+ requires Babel 12.2 or greater.
flaskrequiredThe web framework it extends.
jinja2requiredFor template integration; Flask-Babel v3.0.0+ requires Jinja 3 or greater.
pytzrequiredFor timezone handling; became an explicit dependency in v1.0.0.
werkzeugrequiredFlask's WSGI utility library, had a deprecated import fix in v1.0.0.
Agent activity
25 hits · last 30 days
node
24
Resources
flask-babel — pip install flask-babel · libregistry