l10n.py 1.07 KB
Newer Older
Lukas Fleischer's avatar
Lukas Fleischer committed
1
2
import gettext

3
4
import aurweb.config

Lukas Fleischer's avatar
Lukas Fleischer committed
5
6
7

class Translator:
    def __init__(self):
8
        self._localedir = aurweb.config.get('options', 'localedir')
Lukas Fleischer's avatar
Lukas Fleischer committed
9
10
11
12
13
14
        self._translator = {}

    def translate(self, s, lang):
        if lang == 'en':
            return s
        if lang not in self._translator:
15
            self._translator[lang] = gettext.translation("aurweb",
16
                                                         self._localedir,
Lukas Fleischer's avatar
Lukas Fleischer committed
17
                                                         languages=[lang])
18
        return self._translator[lang].gettext(s)
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40


def get_translator_for_request(request):
    """
    Determine the preferred language from a FastAPI request object and build a
    translator function for it.

    Example:
    ```python
    _ = get_translator_for_request(request)
    print(_("Hello"))
    ```
    """
    lang = request.cookies.get("AURLANG")
    if lang is None:
        lang = aurweb.config.get("options", "default_lang")
    translator = Translator()

    def translate(message):
        return translator.translate(message, lang)

    return translate