FastAPI BABEL
Get pybabbel tools directly within your FastAPI project without hassle.
FastAPI Babel is integrated within FastAPI framework and gives you support of i18n, l10n, date and time locales, and all other pybabel functionalities.
Features:
- I18n (Internationalization)
- Wtform Translation (Lazy Text)
- l10n (Localization)
- Date and time locale
- Decimal, Number locale
- Money and currency locale converter
- locale selector from HTTP header
Support
Python: 3.6 and later (tested on Python 3.6, 3.12) FastAPI: 0.45.0 + PyBabel: All
Installation
pip install fastapi-babel
How to use
- install FastAPI and FastAPI Babel:
pip install fastapi
and
pip install fastapi_babel
- make
babel.pyfile:
from fastapi_babel import Babel, 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.cfgfile
babel.cfg
[python: **.py]
- Create main.py file:
from fastapi_babel import Babel, BabelConfigs, _
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 pybabel
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
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
Why FastAPI Babel CLI is recommanded ?
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 Babel beside fastapi runner files (main.py or run.py), as uvicorn cli will not work.
[========]
Using FastAPI Babel in an API
- create file
babel.pyand write the code below.
from fastapi_babel import Babel, BabelConfigs, BabelMiddleware
configs = BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
)
app.add_middleware(BabelMiddleware, babel_configs=configs)
if __name__ == "__main__":
Babel(configs).run_cli()
- extract messages with following command
python3 babel.py extract -d/--dir {watch_dir}
**Notice: ** watch_dir is your project root directory, where the messages will be extracted.
- Add your own language locale directory, for instance
fa.
python3 babel.py init -l fa
-
Go to ./lang/Fa/.po and add your translations.
-
compile all locale directories.
python3 babel.py compile
from fastapi import FastAPI, Request
from fastapi_babel import _
from .babel import babel
app = FastAPI()
app.add_middleware(BabelMiddleware, babel_configs=BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
))
@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 language from the request header and the locale code. The parameter is
Accept-Language.
How to use Jinja In FastAPI Babel
- Add jinja extension to babel.cfg
[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
- Here is how your
main.pyshould look like.
main.py
from fastapi_babel import Babel, BabelConfigs, BabelMiddleware, _
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request
app = FastAPI()
babel_configs = BabelConfigs(
ROOT_DIR=__file__,
BABEL_DEFAULT_LOCALE="en",
BABEL_TRANSLATION_DIRECTORY="lang",
)
templates = Jinja2Templates(directory="templates")
app.add_middleware(BabelMiddleware, babel_configs=babel_configs, jinja2_templates=templates)
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.htmlfile
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.
-
More features like lazy gettext, please check the Wtform Example
Authors
Contributing
Contributions are always welcome!
Please read contributing.md to get familiar how to get started.
Please adhere to the project's code of conduct.
Feedback And Support
Please open an issue and follow the template, so the community can help you.
Metadata
Release files for fastapi-babel 1.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fastapi_babel-1.0.0.tar.gz | 12.9 kB | Without provenance | Details for fastapi_babel-1.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fastapi_babel-1.0.0-py3-none-any.whl | Python 3 | none | any | Details for fastapi_babel-1.0.0-py3-none-any.whl |
Total release size: 24.7 kB
Release files / fastapi_babel-1.0.0.tar.gz
| Download URL | fastapi_babel-1.0.0.tar.gz |
|---|---|
| Size | 12.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a70005e132b6cfc611a5a02601c63bcd26a1b1cb689d7295be4587c9d35402f3
|
|
BLAKE2b-256 checksum How to use checksums |
ea0d271af537fddc3c08e5f6e36c4e9f12c55d98ff9240a37454125b3c772fd2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.0.1 CPython/3.12.3
|
Release files / fastapi_babel-1.0.0-py3-none-any.whl
| Download URL | fastapi_babel-1.0.0-py3-none-any.whl |
|---|---|
| Size | 11.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9be639b098dd07dfe5b811df318abdd7e282622ac20304d909151f46b09a087d
|
|
BLAKE2b-256 checksum How to use checksums |
d8d5bc9fa86cb3fb3fa040c5841562ea874bbdc069b660739a314cf75df06200
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.0.1 CPython/3.12.3
|
Security for fastapi-babel 1.0.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.