Skip to content

Commit b6defc6

Browse files
authored
Fix i18n target language error when concurrent (#970)
1 parent 8cbea57 commit b6defc6

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

backend/common/context.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ class TypedContextProtocol(Protocol):
1919
device: str | None
2020

2121
permission: str | None
22+
language: str
2223

2324

2425
class TypedContext(TypedContextProtocol, _Context):

backend/common/i18n.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
import yaml
88

9+
from starlette_context.errors import ContextDoesNotExistError
10+
11+
from backend.common.context import ctx
912
from backend.core.conf import settings
1013
from backend.core.path_conf import LOCALE_DIR
1114

@@ -15,9 +18,21 @@ class I18n:
1518

1619
def __init__(self) -> None:
1720
self.locales: dict[str, dict[str, Any]] = {}
18-
self.current_language: str = settings.I18N_DEFAULT_LANGUAGE
1921
self.load_locales()
2022

23+
@property
24+
def current_language(self) -> str:
25+
"""获取当前请求的语言"""
26+
try:
27+
return ctx.language
28+
except (AttributeError, LookupError, ContextDoesNotExistError):
29+
return settings.I18N_DEFAULT_LANGUAGE
30+
31+
@current_language.setter
32+
def current_language(self, language: str) -> None:
33+
"""设置当前请求的语言"""
34+
ctx.language = language
35+
2136
def load_locales(self) -> None:
2237
"""加载语言文本"""
2338
patterns = [

0 commit comments

Comments
 (0)