123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- # -*- coding: utf-8 -*-
- from functools import wraps
- from fastapi import HTTPException
- from httpx import AsyncClient, URL
- def api_exception(func):
- @wraps(func)
- async def wrapper(*args, **kwargs):
- try:
- r = await func(*args, **kwargs)
- except Exception:
- raise HTTPException(
- status_code=500,
- detail="The server did not receive a correct response from the up stream server.",
- )
- else:
- return r
- return wrapper
- class Service:
- def __init__(self, client: AsyncClient) -> None:
- self._client = client
- @api_exception
- async def _get(
- self, url: URL, params: dict | None = None, headers: dict | None = None
- ) -> dict:
- raw_response = await self._client.get(url, params=params, headers=headers)
- # logger.debug(f'{url} - elapsed: {raw_response.elapsed.total_seconds()}')
- return raw_response.json()
- @api_exception
- async def _post(
- self,
- url: URL,
- params: dict | None = None,
- payload: dict | None = None,
- headers: dict | None = None,
- ) -> dict:
- raw_response = await self._client.post(
- url, params=params, json=payload, headers=headers
- )
- # logger.debug(f'{url} - elapsed: {raw_response.elapsed.total_seconds()}')
- return raw_response.json()
|