Add i18n support for response message (#753)

* feat: i18n support

* Optimize i18n

* Update the locale in the code

* Update the zh-CN file

* Update the en-US file

* Update the reload filter

* Update locale success plugin value

* Fix lint

* Update pydantic error message translation

* Update to minimal implementation

* Fix minimal missing code
This commit is contained in:
Dylan
2025-08-15 19:57:10 +08:00
committed by GitHub
parent 4500dd0128
commit cd48bb4210
16 changed files with 340 additions and 134 deletions

View File

@ -8,11 +8,9 @@ from starlette.middleware.cors import CORSMiddleware
from uvicorn.protocols.http.h11_impl import STATUS_PHRASES
from backend.common.exception.errors import BaseExceptionMixin
from backend.common.i18n import i18n, t
from backend.common.response.response_code import CustomResponseCode, StandardResponseCode
from backend.common.response.response_schema import response_base
from backend.common.schema import (
CUSTOM_VALIDATION_ERROR_MESSAGES,
)
from backend.core.conf import settings
from backend.utils.serializers import MsgSpecJSONResponse
from backend.utils.trace_id import get_request_trace_id
@ -46,18 +44,20 @@ async def _validation_exception_handler(request: Request, exc: RequestValidation
"""
errors = []
for error in exc.errors():
custom_message = CUSTOM_VALIDATION_ERROR_MESSAGES.get(error['type'])
if custom_message:
ctx = error.get('ctx')
if not ctx:
error['msg'] = custom_message
else:
ctx_error = ctx.get('error')
if ctx_error:
error['msg'] = custom_message.format(**ctx)
error['ctx']['error'] = (
ctx_error.__str__().replace("'", '"') if isinstance(ctx_error, Exception) else None
)
# 非 en-US 语言下,使用自定义错误信息
if i18n.current_language != 'en-US':
custom_message = t(f'pydantic.{error["type"]}')
if custom_message:
ctx = error.get('ctx')
if not ctx:
error['msg'] = custom_message
else:
ctx_error = ctx.get('error')
if ctx_error:
error['msg'] = custom_message.format(**ctx)
error['ctx']['error'] = (
ctx_error.__str__().replace("'", '"') if isinstance(ctx_error, Exception) else None
)
errors.append(error)
error = errors[0]
if error.get('type') == 'json_invalid':