diff options
| author | 2019-08-04 20:22:27 +0200 | |
|---|---|---|
| committer | 2019-08-04 20:22:27 +0200 | |
| commit | 528c5749ff410cbcdd3982d30ba4d966860282ef (patch) | |
| tree | 0cc1494d1c217a66a7e92a1215364116cdbf9b8d | |
| parent | Handle more API status codes. (diff) | |
Raise specific exception for non-200s.
| -rw-r--r-- | bot/api.py | 30 |
1 files changed, 21 insertions, 9 deletions
diff --git a/bot/api.py b/bot/api.py index 2e1a239ba..4f4ffeff3 100644 --- a/bot/api.py +++ b/bot/api.py @@ -1,3 +1,4 @@ +import typing from urllib.parse import quote as quote_url import aiohttp @@ -5,6 +6,10 @@ import aiohttp from .constants import Keys, URLs +class ResponseCodeError(typing.NamedTuple, ValueError): + response: aiohttp.ClientResponse + + class APIClient: def __init__(self, **kwargs): auth_headers = { @@ -16,33 +21,40 @@ class APIClient: else: kwargs['headers'] = auth_headers - self.session = aiohttp.ClientSession( - **kwargs, - raise_for_status=True - ) + self.session = aiohttp.ClientSession(**kwargs) @staticmethod def _url_for(endpoint: str): return f"{URLs.site_schema}{URLs.site_api}/{quote_url(endpoint)}" - async def get(self, endpoint: str, *args, **kwargs): + def maybe_raise_for_status(self, response: aiohttp.ClientResponse, should_raise: bool): + if should_raise and response.status_code >= 400: + raise ResponseCodeError(response=response) + + async def get(self, endpoint: str, *args, raise_for_status: bool = True, **kwargs): async with self.session.get(self._url_for(endpoint), *args, **kwargs) as resp: + self.maybe_raise_for_status(resp, raise_for_status) return await resp.json() - async def patch(self, endpoint: str, *args, **kwargs): + async def patch(self, endpoint: str, *args, raise_for_status: bool = True, **kwargs): async with self.session.patch(self._url_for(endpoint), *args, **kwargs) as resp: + self.maybe_raise_for_status(resp, raise_for_status) return await resp.json() - async def post(self, endpoint: str, *args, **kwargs): + async def post(self, endpoint: str, *args, raise_for_status: bool = True,**kwargs): async with self.session.post(self._url_for(endpoint), *args, **kwargs) as resp: + self.maybe_raise_for_status(resp, raise_for_status) return await resp.json() - async def put(self, endpoint: str, *args, **kwargs): + async def put(self, endpoint: str, *args, raise_for_status: bool = True, **kwargs): async with self.session.put(self._url_for(endpoint), *args, **kwargs) as resp: + self.maybe_raise_for_status(resp, raise_for_status) return await resp.json() - async def delete(self, endpoint: str, *args, **kwargs): + async def delete(self, endpoint: str, *args, raise_for_status: bool = True, **kwargs): async with self.session.delete(self._url_for(endpoint), *args, **kwargs) as resp: if resp.status == 204: return None + + self.maybe_raise_for_status(resp, raise_for_status) return await resp.json() |