Quart-Babel

raw JSON →
1.0.7 verified Sat May 09 auth: no python

Implements i18n and l10n support for Quart, the async Python web microframework. Current version 1.0.7. Release cadence is irregular, with several breaking changes in recent versions.

pip install quart-babel
error TypeError: can't use async function in non-async context
cause Using 'await' with gettext/format_date, which are synchronous in versions >=1.0.6.
fix
Remove 'await' from gettext, format_date, etc. They are synchronous functions.
error AttributeError: module 'quart_babel' has no attribute 'Babel'
cause Importing from wrong module (e.g., 'from quart_babel.babel import Babel').
fix
Use 'from quart_babel import Babel'.
error RuntimeError: No current application context
cause Calling gettext outside of a Quart request context (e.g., at module level).
fix
Ensure gettext is called within a route or template, or use lazy_gettext outside context.
error ImportError: cannot import name 'format_date' from 'quart_babel'
cause Trying to import from a submodule like 'quart_babel.dates' in old versions.
fix
Use 'from quart_babel import format_date' directly.
breaking In version 1.0.6, the extension was rewritten as a copy of Flask-Babel, removing the ASGI middleware. All functions (gettext, format_date, etc.) are now synchronous, not async. Update your routes and templates accordingly.
fix Remove 'await' calls from gettext, format_date, etc. Import directly from quart_babel.
breaking Version 1.0.0 introduced ASGI middleware for locale/timezone detection, which broke compatibility with Quart-WTF and other extensions. Version 1.0.6 removed that middleware again.
fix Upgrade to >=1.0.6, which reverts to Flask-Babel style without middleware.
gotcha Quart-Babel does not automatically detect the browser's language. You must implement your own locale selector (e.g., from request headers).
fix Pass a locale_selector function when initializing Babel: Babel(app, locale_selector=lambda: request.headers.get('Accept-Language', 'en')[0:2])
gotcha Lazy gettext (lazy_gettext) cannot be used directly in route decorators because it's evaluated at template rendering time. Use it in form definitions or with callables.
fix Store lazy_gettext in a lambda or function, or use it only inside templates and forms.

Basic Quart-Babel setup with a simple route using gettext.

import os
from quart import Quart
from quart_babel import Babel, gettext, set_locale

app = Quart(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = os.environ.get('BABEL_DEFAULT_LOCALE', 'en')
babel = Babel(app)

@app.route('/')
async def index():
    return gettext('Hello World')

if __name__ == '__main__':
    app.run()