Get pybabbel tools directly within your FastAPI project without hassle.
FastAPI Babel is will be integrated within FastAPI framework and gives you support of i18n, l10n, date and time locales and all other pybabel functionalities.
- I18n (Internationalization)
- l10n (Localization)
- Date and time locale
- Decimal, Number locale
- Money and currency locale converter
- locale selector from http header
Python: 3.6 and later (tested on Python 3.6, 3.7, 3.8, and 3.9) FastAPI: 0.45.0 + PyBabel: All
pip install fastapi-babel
- install FastAPI and FastAPI Babel:
pip install fastapi
and
pip install fastapi_babel
- make
babel.py
file:
from fastapi_babel import Babel
from fastapi_babel import BabelConfigs
configs = BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
)
babel = Babel(configs=configs)
if __name__ == "__main__":
babel.run_cli()
- make
babel.cfg
file
babel.cfg
[python: **.py]
- Create main.py file:
from fastapi_babel import Babel
from fastapi_babel import BabelConfigs
from fastapi_babel import _
configs = BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
)
babel = Babel(configs=configs)
def main():
babel.locale = "en"
en_text = _("Hello World")
print(en_text)
babel.locale = "fa"
fa_text = _("Hello World")
print(fa_text)
if __name__ == "__main__":
main()
pybabel extract -F babel.cfg -o messages.pot .
- Initialize pybabble
pybabel init -i messages.pot -d lang -l fa
-
Goto lang/YOUR_LANGUAGE_CODE/LC_MESSAGES/messages.po and add your translation to your messages.
-
Go back to the root folder and Compile
pybabel compile -d lang
- Run
main.py
python3 main.py
- Enjoy
Install click at first:
pip install click
- Add this snippet to your FasAPI code:
...
babel.run_cli()
...
- Now just follow the documentation from step 5.
For more information just take a look at help flag of main.py
python main.py --help
FastAPI Babel CLI will eliminate the need of concering the directories and paths, so you can concentrate on the project and spend less time on going forward and backward. You only need to specify domain name, babel.cfg and** localization directory **.
NOTICE: Do not use FastAPI Babbel
beside fastapi runner files (main.py
or run.py
), as uvicorn cli will not work.
[========]
- create file
babel.py
and write the code below.
from fastapi_babel import Babel
from fastapi_babel import BabelConfigs
configs = BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
)
babel = Babel(configs=configs)
if __name__ == "__main__":
babel.run_cli()
- Extract messages with following command
python3 babel.py extract -d/--dir {watch_dir}
**Notice: ** watch_dir is your project root directory, or where you want to extract the messages into that directory.
- add your own langauge locale directory, for instance
fa
.
python3 babel.py init -l fa
-
go to ./lang/Fa/.po and add your translations.
-
compile all locale directorties.
python3 babel.py compile
from fastapi import FastAPI, Request
from fastapi_babel import _
from .babel import babel
app = FastAPI()
babel.init_app(app)
@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
return id + _("Hello World")
- Now you can control your translation langauge from header of request and locale code. The parameter is
Accept-Laguage
.
- Add jinja extension to babel.cfg
[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
- Here is how your
main.py
should look like.
main.py
from fastapi import FastAPI, Request
from fastapi_babel import Babel
from fastapi_babel import BabelConfigs
from fastapi_babel import _
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates")
configs = BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
)
app = FastAPI()
babel = Babel(app, configs=configs)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
return templates.TemplateResponse("item.html", {"request": request, "id": id})
- Here is sample
index.html
file
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{_("Hello World")}}</h1>
</body>
</html>
- Now just follow the documentation from step 5.
Contributions are always welcome!
Please read contributing.md
to get familiar how to get started.
Please adhere to the project's code of conduct
.
Please open an issue and follow the template, so the community can help you.