fix(i18n): pass locale to background threads via thread-local storage

Background threads (graph building, simulation prep, report generation,
profile generation) now inherit the requesting user's locale preference.
Previously these fell back to 'zh' because Flask request context was
unavailable in spawned threads.
This commit is contained in:
ghostubborn
2026-04-01 16:55:51 +08:00
parent 592ee52f59
commit 7c07237544
9 changed files with 54 additions and 14 deletions

View File

@@ -4,7 +4,7 @@
from .file_parser import FileParser
from .llm_client import LLMClient
from .locale import t, get_locale, get_language_instruction
from .locale import t, get_locale, set_locale, get_language_instruction
__all__ = ['FileParser', 'LLMClient', 't', 'get_locale', 'get_language_instruction']
__all__ = ['FileParser', 'LLMClient', 't', 'get_locale', 'set_locale', 'get_language_instruction']

View File

@@ -1,7 +1,10 @@
import json
import os
import threading
from flask import request, has_request_context
_thread_local = threading.local()
_locales_dir = os.path.join(os.path.dirname(__file__), '..', '..', '..', 'locales')
# Load language registry
@@ -17,10 +20,15 @@ for filename in os.listdir(_locales_dir):
_translations[locale_name] = json.load(f)
def set_locale(locale: str):
"""Set locale for current thread. Call at the start of background threads."""
_thread_local.locale = locale
def get_locale() -> str:
if has_request_context():
return request.headers.get('Accept-Language', 'zh')
return 'zh'
return getattr(_thread_local, 'locale', 'zh')
def t(key: str, **kwargs) -> str: