/
liquid-g
/
liquid-code
Обзор
Документация
Войти
/
liquid-g
/
liquid-code
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop-0.4
src/liquidcode/kernel/response_normalizer.py
50 строк
2 KB
User
0.4.11 - интеграция Pydantic для автоматической сериализации и десериализации моделей
06 июл 2026, 14:58
06 июл 2026, 14:58
d729128
Код
Авторство
О чём код?
from typing import Any, Type from ..contracts import Response from ..pydantic import serialize_response def normalize_response(result: Any, response_class: Type[Response]) -> Response: """ Преобразует результат контроллера в объект Response. Поддерживает: - Response (возврат как есть) - tuple (data, status) или (data, status, headers) - Pydantic модели (автоматическая сериализация) - любой другой тип → оборачивается в Response со статусом 200 """ if isinstance(result, response_class): return result elif isinstance(result, tuple): if len(result) == 2: data, status = result # Сериализуем Pydantic модели data = serialize_response(data) return response_class( content=data, status=status, headers={'Content-Type': 'application/json'} ) elif len(result) == 3: data, status, headers = result # Сериализуем Pydantic модели data = serialize_response(data) return response_class( content=data, status=status, headers=headers ) else: return response_class( content={'error': 'Некорректный формат ответа'}, status=500, headers={'Content-Type': 'application/json'} ) else: # Сериализуем Pydantic модели serialized = serialize_response(result) return response_class( content=serialized, status=200, headers={'Content-Type': 'application/json'} )