Anbarryprojects / fastapi-babel

FastAPI babel support pybable tools like translation of text, formatting of dates, times and numbers, and time zones.
MIT License
46 stars 14 forks source link

Fastapi Babel Logo #2

Closed Legopapurida closed 1 year ago

Legopapurida commented 2 years ago

fastapi-babel

Legopapurida commented 2 years ago

FastAPI BABEL

Fastapi babel is a tool what supports i18n, l10n, date and time locales and all pybabel functionalities easily that integrated with fastapi framework.

Features:

Support

Python: 3.6 and later (tested against 3.6, 3.7, 3.8 and 3.9) FastAPI: 0.45.0 + PyBabel: All

Installation

pip install fastapi-babel

How to use 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()
  1. initializing pybabel init -i messages.pot -d lang -l fa

  2. Goto lang/fa/LC_MESSAGES/messages.po and add your translation to your messages.

  3. compiling pybabel compile -d lang

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

Why FastAPI Babel Cli is recommended?

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.

Using FastAPI Babel in an API