service.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. from functools import wraps
  3. from fastapi import HTTPException
  4. from httpx import AsyncClient, URL
  5. def api_exception(func):
  6. @wraps(func)
  7. async def wrapper(*args, **kwargs):
  8. try:
  9. r = await func(*args, **kwargs)
  10. except Exception:
  11. raise HTTPException(
  12. status_code=500,
  13. detail="The server did not receive a correct response from the up stream server.",
  14. )
  15. else:
  16. return r
  17. return wrapper
  18. class Service:
  19. def __init__(self, client: AsyncClient) -> None:
  20. self._client = client
  21. @api_exception
  22. async def _get(
  23. self, url: URL, params: dict | None = None, headers: dict | None = None
  24. ) -> dict:
  25. raw_response = await self._client.get(url, params=params, headers=headers)
  26. # logger.debug(f'{url} - elapsed: {raw_response.elapsed.total_seconds()}')
  27. return raw_response.json()
  28. @api_exception
  29. async def _post(
  30. self,
  31. url: URL,
  32. params: dict | None = None,
  33. payload: dict | None = None,
  34. headers: dict | None = None,
  35. ) -> dict:
  36. raw_response = await self._client.post(
  37. url, params=params, json=payload, headers=headers
  38. )
  39. # logger.debug(f'{url} - elapsed: {raw_response.elapsed.total_seconds()}')
  40. return raw_response.json()