DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 964,423 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Piotrek M.
Piotrek M.

Posted on

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

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.