feat: Backend i18n

This commit is contained in:
fit2cloud-chenyw
2025-07-07 14:16:05 +08:00
parent cd26d6594e
commit 17fd6ffbf7
8 changed files with 124 additions and 9 deletions
+6 -1
View File
@@ -1,7 +1,7 @@
from typing import Annotated
import jwt
from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, Request, status
# from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from pydantic import ValidationError
@@ -13,6 +13,7 @@ from common.core import security
from common.core.config import settings
from common.core.db import get_session
from apps.system.models.user import UserModel
from common.utils.locale import I18n
reusable_oauth2 = XOAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
)
@@ -22,7 +23,11 @@ reusable_oauth2 = XOAuth2PasswordBearer(
SessionDep = Annotated[Session, Depends(get_session)]
TokenDep = Annotated[str, Depends(reusable_oauth2)]
i18n = I18n()
async def get_i18n(request: Request):
return i18n(request)
Trans = Annotated[I18n, Depends(get_i18n)]
async def get_current_user(session: SessionDep, token: TokenDep) -> BaseUserDTO:
try:
payload = jwt.decode(
+46
View File
@@ -0,0 +1,46 @@
from pathlib import Path
import json
from typing import Dict, Optional
from fastapi import Request
class I18n:
def __init__(self, locale_dir: str = "locales"):
self.locale_dir = Path(locale_dir)
self.translations: Dict[str, Dict[str, str]] = {}
self.load_translations()
def load_translations(self):
if not self.locale_dir.exists():
self.locale_dir.mkdir()
return
for lang_file in self.locale_dir.glob("*.json"):
with open(lang_file, 'r', encoding='utf-8') as f:
self.translations[lang_file.stem.lower()] = json.load(f)
def get_language(self, request: Request) -> str:
accept_language = request.headers.get('accept-language', 'en')
primary_lang = accept_language.split(',')[0].lower()
return primary_lang if primary_lang in self.translations else 'zh-cn'
def __call__(self, request: Request) -> 'I18nHelper':
return I18nHelper(self, request)
class I18nHelper:
def __init__(self, i18n: I18n, request: Request):
self.i18n = i18n
self.request = request
self.lang = i18n.get_language(request)
def __call__(self, key: str, **kwargs) -> str:
lang_data = self.i18n.translations.get(self.lang, {})
text = lang_data.get(key, key) # 找不到则返回原key
if kwargs:
try:
return text.format(**kwargs)
except (KeyError, ValueError):
return text
return text