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