Skip to main content

FastAPI-babel is an extenstion for I18n and I10n support in FastAPI, based on babel and pytz.

Project description

FastAPI BABEL

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.

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.7, 3.8, and 3.9) FastAPI: 0.45.0 + PyBabel: All

Installation

pip install fastapi-babel

How to use

  1. install FastAPI and FastAPI Babel:

pip install fastapi

and

pip install fastapi_babel

  1. 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()
  1. make babel.cfg file

babel.cfg

[python: **.py]
  1. 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()
  1. Extract the massage

pybabel extract -F babel.cfg -o messages.pot .

  1. Initialize pybabble

pybabel init -i messages.pot -d lang -l fa

  1. Goto lang/YOUR_LANGUAGE_CODE/LC_MESSAGES/messages.po and add your translation to your messages.

  2. Go back to the root folder and Compile

pybabel compile -d lang

  1. Run main.py

python3 main.py

  1. Enjoy
  • FastAPI Babel Commands

Install click at first: pip install click

  1. Add this snippet to your FasAPI code:
...
babel.run_cli()
...
  1. 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 Babbel beside fastapi runner files (main.py or run.py), as uvicorn cli will not work.

[========]

Using FastAPI Babel in an API

  • 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()
  1. 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.

  1. add your own langauge locale directory, for instance fa.

python3 babel.py init -l fa

  1. go to ./lang/Fa/.po and add your translations.

  2. 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")
  1. Now you can control your translation langauge from header of request and locale code. The parameter is Accept-Laguage.

Screenshot: Screenshot 1

How to use Jinja In FastAPI Babel

  1. Add jinja extension to babel.cfg
[python: **.py]
[jinja2: **/templates/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
  1. 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)
babel.install_jinja(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})
  1. 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>
  1. Now just follow the documentation from step 5.

  2. 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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fastapi-babel-0.0.8.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fastapi_babel-0.0.8-py3-none-any.whl (9.3 kB view details)

Uploaded Python 3

File details

Details for the file fastapi-babel-0.0.8.tar.gz.

File metadata

  • Download URL: fastapi-babel-0.0.8.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.9

File hashes

Hashes for fastapi-babel-0.0.8.tar.gz
Algorithm Hash digest
SHA256 53933cf3bf5fcd5fa3fc86b57f5998da92c61ca7476e430c6626eed352b4c774
MD5 c2d246d58637343ddb190d2b956e25df
BLAKE2b-256 59b61236cfdab3a79a74a228ad989ee93e3340b628a2c2cde46f27ac147f7a07

See more details on using hashes here.

File details

Details for the file fastapi_babel-0.0.8-py3-none-any.whl.

File metadata

  • Download URL: fastapi_babel-0.0.8-py3-none-any.whl
  • Upload date:
  • Size: 9.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.10.9

File hashes

Hashes for fastapi_babel-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 da1497f64e3a087297995ba862bd72104375de0082235a420ae03f4b10de150f
MD5 42669cf164df5e6ad2ae94443c50f48b
BLAKE2b-256 0c561d25edceb19ddbcb39675086efd66daef71ff8cfacc5054cb513f80eaa9f

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page