FastAPI Translation
pip install fastapi-and-babel
Other methods and modules exists, this is simple to use and works.
from fastapi import FastAPI, Request
from fastapi_and_babel.translator import FastAPIAndBabel
from fastapi_and_babel import gettext as _
app = FastAPI()
app_language = "en" # or zh, es, fr etc..
translator = FastAPIAndBabel(root_dir=__file__, app=app, translation_dir="lang")
# root dir __file__ means the directory of this file, app is the FastAPI app
translator.set_default_locale(app_language)
template = Jinja2Templates(directory="templates")
template.env.globals['_'] = _ # Important for Jinja2 to use _
# Python Translation syntax
_("String to translate")
Jinja Translation Syntax
{{ _('String to translate') }}
Initializing Translation
Create a file babel.cfg
in the root of your project with the following content:
[ignore: **/venv/**]
[python: **.py]
[jinja2: **/templates/**.html]
- any ignore needs to be added before
The folderlang
will be used for translation. The first step is usingpybabel
to initialize the translation, it takes all .py files and .html
pybabel extract -F babel.cfg -o lang/messages.pot .
Create and Updating Translation
pybabel init -i lang/messages.pot -d lang -l en
pybabel init -i lang/messages.pot -d lang -l zh
Afterward, compile the translation
pybabel compile -d lang
To update the translation, extract the messages again and update the translation
pybabel extract -F babel.cfg -o lang/messages.pot .
pybabel update -i lang/messages.pot -d lang