11"""Example with which we test UI elements with L10N support."""
22
3- import locale
3+ # import locale
44import os
55import random
66from contextlib import asynccontextmanager
77from typing import Annotated
88
9- from fastapi import FastAPI , responses , Header
9+ from fastapi import FastAPI , responses , Header , Request
10+ from starlette .middleware .base import BaseHTTPMiddleware
1011from pydantic import BaseModel
1112
1213from nc_py_api import NextcloudApp
2021 UiActionFileInfo
2122)
2223
23- import gettext
24+ from gettext import gettext as _ , translation
2425
2526# ../locale/<lang>/LC_MESSAGES/<app_id>.(mo|po)
26- localedir = os .path .join (os .path .dirname (os .path .dirname (__file__ )), "locale" )
27- locale .setlocale (locale .LC_ALL )
28- my_l10n = gettext .translation (
29- os .getenv ("APP_ID" ), localedir , fallback = True , languages = ["en" ] # English is always available and is the default
30- )
31- my_l10n .install ()
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()
33+
34+ # _ = my_l10n.gettext
35+ # _n = my_l10n.ngettext
36+
37+
38+ class LocalizationMiddleware (BaseHTTPMiddleware ):
39+ async def dispatch (self , request : Request , call_next ):
40+ localedir = os .path .join (os .path .dirname (os .path .dirname (__file__ )), "locale" )
41+ request_lang = request .headers .get ('Accept-Language' , 'en' )
42+ print (f"DEBUG: lang={ request_lang } " )
43+ translator = translation (
44+ os .getenv ("APP_ID" ), localedir , languages = [request_lang ], fallback = True
45+ )
46+ translator .install ()
47+ response = await call_next (request )
48+ return response
3249
33- _ = my_l10n .gettext
34- _n = my_l10n .ngettext
3550
3651@asynccontextmanager
3752async def lifespan (app : FastAPI ):
@@ -42,6 +57,7 @@ async def lifespan(app: FastAPI):
4257
4358APP = FastAPI (lifespan = lifespan )
4459APP .add_middleware (AppAPIAuthMiddleware )
60+ APP .add_middleware (LocalizationMiddleware )
4561
4662SETTINGS_EXAMPLE = SettingsForm (
4763 id = "settings_example" ,
@@ -170,6 +186,8 @@ async def lifespan(app: FastAPI):
170186
171187def enabled_handler (enabled : bool , nc : NextcloudApp ) -> str :
172188 print (f"enabled={ enabled } " )
189+
190+ z = _ ("Test menu" )
173191 if enabled :
174192 nc .ui .resources .set_initial_state (
175193 "top_menu" ,
0 commit comments