Closed Legopapurida closed 1 year ago
Fastapi babel is a tool what supports i18n, l10n, date and time locales and all pybabel functionalities easily that integrated with fastapi framework.
Python: 3.6 and later (tested against 3.6, 3.7, 3.8 and 3.9) FastAPI: 0.45.0 + PyBabel: All
pip install fastapi-babel
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 .
initializing
pybabel init -i messages.pot -d lang -l fa
Goto lang/fa/LC_MESSAGES/messages.po and add your translation to your messages.
compiling
pybabel compile -d lang
Install click at first:
pip install click
Add this snippet to your code:
...
babel.run_cli()
...
Now you can follow those parts mentioned above for the message extracting process.
For more information you can check helpers of babel cli:
python main.py --help
when you are creating an application at a production level where you will deploy it on a server you may not find the right directory and paths of babel domain and config files, but FastAPI Babel Cli will do it perfectly without any concern about that. you only need to specify domain name, babel.cfg and localization directory .
NOTICE: you never use it beside fastapi runner file line main.py
or run.py
, because uvicorn cli will not work anymore.
You have better separate a babel cli runner file beside of fastapi runner file, by the way, you will not overwhelm with failure at uvicorn cli.