Изменение языка единоразово для всех последующих запросов
This commit is contained in:
parent
6efbb4285f
commit
4215a62b6c
2 changed files with 25 additions and 25 deletions
|
|
@ -1,10 +1,6 @@
|
|||
import os
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import polib
|
||||
from docutils.nodes import entry
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
from fastapi import APIRouter, HTTPException, Depends, Response, Request
|
||||
from starlette.responses import FileResponse
|
||||
from services.settings_service import SettingsService
|
||||
from utils.i18n import get_translations, _
|
||||
|
|
@ -143,26 +139,27 @@ async def export_wifi(translations: Translations = Depends(get_translations("api
|
|||
media_type="application/json"
|
||||
)
|
||||
|
||||
@router.get("/{locale}/{domain}")
|
||||
async def get_translations(locale: str, domain: str):
|
||||
@router.post("/set_language")
|
||||
def set_language(locale: str, response: Response, request: Request):
|
||||
"""
|
||||
|
||||
Устанавливает куку locale для смены языка пользователя.
|
||||
Args:
|
||||
locale:
|
||||
domain:
|
||||
|
||||
locale (str): Используемый язык.
|
||||
Returns:
|
||||
|
||||
dict: Сообщение об успешной установке языка.
|
||||
"""
|
||||
try:
|
||||
po_file = Path(f"locales/{locale}/LC_MESSAGES/{domain}.po")
|
||||
if not po_file.exists():
|
||||
logger.warning(f"Файл интернационализации для {locale} и домена {domain} не найдены")
|
||||
raise HTTPException(status_code=404, detail=f"Файл интернационализации для {locale} и домена {domain} не найдены")
|
||||
po = polib.pofile(str(po_file))
|
||||
translations = {entry.msgid: entry.msgstr or entry.msgid for entry in po}
|
||||
logger.info(f"Загрузка {len(translations)} перевода для локали {locale} и домена {domain}")
|
||||
return translations
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка загрузки перевода для локали {locale} и домена {domain}: {str(e)}")
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка на сервере: {str(e)}")
|
||||
translations = get_translations("api_v1")(request)
|
||||
lc_messages_path = os.path.join(os.path.dirname(__file__), '..', '..', 'locales', locale, 'LC_MESSAGES')
|
||||
if not os.path.isdir(lc_messages_path):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=translations.gettext("Язык '{locale}' не поддерживается.").format(locale=locale)
|
||||
)
|
||||
has_mo_or_po = any(f.endswith('.mo') or f.endswith('.po') for f in os.listdir(lc_messages_path))
|
||||
if not has_mo_or_po:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=translations.gettext("Язык '{locale}' не поддерживается (нет файлов переводов).").format(locale=locale)
|
||||
)
|
||||
response.set_cookie(key="locale", value=locale, path="/", httponly=True)
|
||||
return {"message": translations.gettext("Язык успешно установлен: {locale}").format(locale=locale)}
|
||||
|
|
@ -21,7 +21,10 @@ def get_translations(domain: str = "api_v1") -> callable:
|
|||
# Проверяем параметр запроса 'locale', если он есть
|
||||
locale = request.query_params.get("locale")
|
||||
if not locale:
|
||||
# Если параметр отсутствует, используем заголовок Accept-Language
|
||||
# Если параметр отсутствует, проверяем куку 'locale'
|
||||
locale = request.cookies.get("locale")
|
||||
if not locale:
|
||||
# Если куки нет, используем заголовок Accept-Language
|
||||
locale = request.headers.get("Accept-Language", "ru").split(",")[0].split("-")[0]
|
||||
|
||||
try:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue