From 5eac9b3f31e252b414358e95ceb5678d69e0b3e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=99=B4=E7=8C=AB?= Date: Sun, 15 Mar 2026 09:41:23 +0900 Subject: [PATCH] fix: default i18n locale from system locale --- src/common/i18n/loaders.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/common/i18n/loaders.py b/src/common/i18n/loaders.py index bdd9ee12..7ae623d6 100644 --- a/src/common/i18n/loaders.py +++ b/src/common/i18n/loaders.py @@ -4,6 +4,7 @@ from pathlib import Path from string import Formatter import json +import locale from .exceptions import ( DuplicateTranslationKeyError, @@ -13,7 +14,7 @@ from .exceptions import ( ) _FORMATTER = Formatter() -DEFAULT_LOCALE = "zh-CN" +_FALLBACK_DEFAULT_LOCALE = "zh-CN" PLURAL_CATEGORIES = {"zero", "one", "two", "few", "many", "other"} TranslationValue = str | dict[str, str] @@ -50,6 +51,27 @@ def normalize_locale(locale: str) -> str: return "-".join(normalized_parts) +def _detect_default_locale() -> str: + try: + system_locale, _encoding = locale.getlocale() + except (TypeError, ValueError, locale.Error): + system_locale = None + + if system_locale: + try: + normalized_locale = normalize_locale(system_locale) + except InvalidLocaleError: + normalized_locale = "" + + if normalized_locale and (get_locales_root() / normalized_locale).is_dir(): + return normalized_locale + + return _FALLBACK_DEFAULT_LOCALE + + +DEFAULT_LOCALE = _detect_default_locale() + + def to_babel_locale(locale: str) -> str: return normalize_locale(locale).replace("-", "_")