-
Notifications
You must be signed in to change notification settings - Fork 33
/
i18n.py
59 lines (46 loc) · 1.69 KB
/
i18n.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
""" handle internationalization """
import os
import gettext as gettextlib
import threading
localedir = os.path.join(os.path.dirname(__file__), "locale")
DOMAIN = "messages"
thread_local_data = threading.local()
thread_local_data.locale = "en_US"
locales_metadata = [
{"code": "en_US", "name": "English (US)", "slug": ""},
{"code": "de_DE", "name": "Deutsch", "slug": "de/"},
{"code": "fr_FR", "name": "Français", "slug": "fr/"},
{"code": "pl_PL", "name": "Polski", "slug": "pl/"},
{"code": "pt_BR", "name": "Português do Brasil", "slug": "pt-br/"},
{"code": "ro_RO", "name": "Română", "slug": "ro/"},
]
default_locale = "en_US" # pylint: disable=invalid-name
# find out all supported locales in locale directory
locales = []
for dirpath, dirnames, filenames in os.walk(localedir):
for dirname in dirnames:
locales.append(dirname)
break
all_translations = {}
for locale_name in locales:
all_translations[locale_name] = gettextlib.translation(
DOMAIN, localedir, [locale_name]
)
def gettext(message):
"""translate message based on current locale"""
return all_translations[thread_local_data.locale].gettext(message)
# pylint: disable=invalid-name
def ngettext(singular, plural, n):
"""translation strings with plurals"""
return all_translations[thread_local_data.locale].ngettext(singular, plural, n)
# pylint: disable=invalid-name
def setLocale(locale):
"""set thread data locale"""
if locale in locales:
thread_local_data.locale = locale
if __name__ == "__main__":
# for test purpose
for dirpath, dirnames, filenames in os.walk(localedir):
for dirname in dirnames:
print(dirname)
break