Search code examples
pythonfastapigettext

How to create multilingual web pages with fastapi-babel?


I'm thinking of creating a multilingual web page with fastapi-babel.

I have configured according to the documentation. The translation from English to French was successful. However, I created a .po file for another language, translated it, compiled it, but the translated text does not apply.

from fastapi_babel import _
from fastapi_babel.middleware import InternationalizationMiddleware as I18nMiddleware
from fastapi_babel import Babel
from fastapi_babel import BabelConfigs

configs = BabelConfigs(
     ROOT_DIR=__file__,
     BABEL_DEFAULT_LOCALE="en",
     BABEL_TRANSLATION_DIRECTORY="lang",
)
logger.info(f"configs: {configs.__dict__}")
babel = babel(configs)
babel.install_jinja(templates)

app.add_middleware(I18nMiddleware, babel=babel)


@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
     babel.locale = "en"
     logger.info(_("Hello World"))
     babel. locale = "fa"
     logger.info(_("Hello World"))
     babel.locale = "ja"
     logger.info(_("Hello World"))
     return templates.TemplateResponse('item.html', {'request': request, 'id': id})

Above, the result will be:

INFO: Hello World
INFO: Bonjour le monde
INFO: Hello World

How can the translation be applied to languages other than French?

enter image description here


Solution

  • I was using the old version 0.0.3. When I changed the version to the latest 0.0.8, the translation was reflected in languages other than French.

    pip install fastapi-babel==0.0.8
    

    Note

    You need restart FastAPI server, after pybabel compile -d lang

    If BABEL_DEFAULT_LOCALE and babel.locale is same, it doesn't translate.

    babel = Babel(
        configs=BabelConfigs(
            ROOT_DIR=__file__,
            BABEL_DEFAULT_LOCALE="en",
            BABEL_TRANSLATION_DIRECTORY="lang",
        )
    )
    
    babel.locale = "en"
    

    When you update translation files.

    Run this 2 commands.

    1. pybabel extract -F babel.cfg -o messages.pot .
    2. pybabel compile -d lang

    Please don't run this command after you create .po file.

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

    If you run, your po file will be reset. (Delete all your translations.)