Files
g2s-aggregator/app/controllers/v1/delivery.py
T
Раис Юсупалиев 150675cc75 006 add controller
2026-03-07 23:54:40 +03:00

67 lines
2.2 KiB
Python

"""Delivery API controller skeleton."""
from fastapi import APIRouter, Depends, HTTPException, Request, status
from app.adapters.delivery_providers.cdek import CDEKProvider
from app.config import Settings
from app.controllers.http_client import build_controller_http_client
from app.repositories.cache.redis_cache import PriceCache
from app.schemas.request import DeliveryRequest
from app.schemas.response import DeliveryPrice
from app.services.aggregator import AggregatorService, AggregatorServiceError
router = APIRouter(prefix="/delivery", tags=["delivery"])
_AGGREGATOR_SERVICE_STATE_KEY = "aggregator_service"
def _build_aggregator_service(settings: Settings) -> AggregatorService:
http_client = build_controller_http_client(
timeout_seconds=settings.adapter.cdek_timeout_seconds
)
providers = (
CDEKProvider.from_adapter_config(
http_client=http_client,
adapter_config=settings.adapter,
),
)
cache = PriceCache.from_repository_config(settings.repository)
service = AggregatorService(
providers=providers,
cache=cache,
weight_round_scale=settings.business_logic.weight_round_scale,
)
return service
async def get_aggregator_service(request: Request) -> AggregatorService:
cached_service = getattr(request.app.state, _AGGREGATOR_SERVICE_STATE_KEY, None)
if cached_service is not None:
return cached_service
settings = request.app.state.settings
service = _build_aggregator_service(settings)
setattr(request.app.state, _AGGREGATOR_SERVICE_STATE_KEY, service)
return service
@router.post(
"/price",
response_model=list[DeliveryPrice],
)
async def get_delivery_price(
delivery_request: DeliveryRequest,
service: AggregatorService = Depends(get_aggregator_service),
) -> list[DeliveryPrice]:
try:
return await service.get_all_prices(delivery_request)
except AggregatorServiceError as exc:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={
"code": "aggregator_service_error",
"message": "Delivery price aggregation is temporarily unavailable.",
},
) from exc