Skip to content

Commit 406b884

Browse files
committed
dev
1 parent b5f6888 commit 406b884

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

lib/main.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Example with which we test UI elements with L10N support."""
22

3-
# import locale
43
import os
54
import random
65
from contextlib import asynccontextmanager
@@ -20,30 +19,31 @@
2019
SettingsForm,
2120
UiActionFileInfo
2221
)
22+
from contextvars import ContextVar
2323

24-
from gettext import gettext as _, translation
24+
from gettext import translation
2525

26-
# ../locale/<lang>/LC_MESSAGES/<app_id>.(mo|po)
27-
# localedir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "locale")
28-
# locale.setlocale(locale.LC_ALL)
29-
# my_l10n = gettext.translation(
30-
# os.getenv("APP_ID"), localedir, fallback=True, languages=["en"] # English is always available and is the default
31-
# )
32-
# my_l10n.install()
26+
LOCALE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "locale")
27+
current_translator = ContextVar("current_translator")
28+
current_translator.set(translation(os.getenv("APP_ID"), LOCALE_DIR, languages=["en"], fallback=True))
3329

34-
# _ = my_l10n.gettext
35-
# _n = my_l10n.ngettext
30+
31+
def _(text):
32+
return current_translator.get().gettext(text)
33+
34+
35+
print(_("UI example")) # this does not work
3636

3737

3838
class LocalizationMiddleware(BaseHTTPMiddleware):
3939
async def dispatch(self, request: Request, call_next):
40-
localedir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "locale")
4140
request_lang = request.headers.get('Accept-Language', 'en')
4241
print(f"DEBUG: lang={request_lang}")
4342
translator = translation(
44-
os.getenv("APP_ID"), localedir, languages=[request_lang], fallback=True
43+
os.getenv("APP_ID"), LOCALE_DIR, languages=[request_lang], fallback=True
4544
)
46-
translator.install()
45+
current_translator.set(translator)
46+
print(_("UI example"))
4747
response = await call_next(request)
4848
return response
4949

0 commit comments

Comments
 (0)