|
1 | 1 | """Example with which we test UI elements with L10N support.""" |
2 | 2 |
|
3 | | -# import locale |
4 | 3 | import os |
5 | 4 | import random |
6 | 5 | from contextlib import asynccontextmanager |
|
20 | 19 | SettingsForm, |
21 | 20 | UiActionFileInfo |
22 | 21 | ) |
| 22 | +from contextvars import ContextVar |
23 | 23 |
|
24 | | -from gettext import gettext as _, translation |
| 24 | +from gettext import translation |
25 | 25 |
|
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)) |
33 | 29 |
|
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 |
36 | 36 |
|
37 | 37 |
|
38 | 38 | class LocalizationMiddleware(BaseHTTPMiddleware): |
39 | 39 | async def dispatch(self, request: Request, call_next): |
40 | | - localedir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "locale") |
41 | 40 | request_lang = request.headers.get('Accept-Language', 'en') |
42 | 41 | print(f"DEBUG: lang={request_lang}") |
43 | 42 | 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 |
45 | 44 | ) |
46 | | - translator.install() |
| 45 | + current_translator.set(translator) |
| 46 | + print(_("UI example")) |
47 | 47 | response = await call_next(request) |
48 | 48 | return response |
49 | 49 |
|
|
0 commit comments