Easy way to internationalize your apps with PyI18n

sectasy0

sectasy

Posted on August 23, 2022

Easy way to internationalize your apps with PyI18n

Introduction

PyI18n is a simple and easy to use internationalization library written for python projects, to help you handle multiple languages in your applications.

How start use PyI18n

First, you have to create your locale files, in my example this will be in locale directory (default PyI18n locales path). In my example I use only two languages polish (pl.yml) and english (en.yml).

Let's write simple FastAPI app.

Project structure for this example



.
├── app.py
└── locales
    ├── en.yml
    └── pl.yml


Enter fullscreen mode Exit fullscreen mode

en.yml



en:
  greetings:
    hello_name: "Hello there {name}! nice to meet you" 


Enter fullscreen mode Exit fullscreen mode

pl.yml



pl:
  greetings:
    hello_name: "Witaj {name}! miło mi cię poznać" 


Enter fullscreen mode Exit fullscreen mode

Assume we're logged in user and we have stored locales in database, otherwise we will just return default locale.



from pyi18n import PyI18n
from fastapi import FastAPI
from typing import Callable, Dict

app: FastAPI = FastAPI()
i18n: PyI18n = PyI18n(('pl', 'en'))

DEFAULT_LOCALE: str = 'en'

_: Callable = i18n.gettext

fake_db: Dict[str, str] = {
    "logged_users": {
        "Piotrek": {
            "locale": "pl"
        },
        "John": {
            "locale": "en",
        },
    }

}

def get_user_locale(name) -> str:
    current_user_locale: str = fake_db["logged_users"].get(name)
    return current_user_locale['locale'] if current_user_locale else DEFAULT_LOCALE


@app.get("/hello/{name}")
def hello_name(name: str):
    locale: str = get_user_locale(name)
    return {"greeting": _(locale, "greetings.hello_name", name=name)}



Enter fullscreen mode Exit fullscreen mode

Now it's time to run our app and check what happens, for testing I used RapidAPI vscode extension (It's something like postman in visual studio code)

Image description

Image description

A full documentation for this module is available at: https://sectasy0.github.io/pyi18n.

If you had some questions or if you see any inaccuracies please let me know in the comments below! Thanks for reading <3

💖 💪 🙅 🚩
sectasy0
sectasy

Posted on August 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related