diff --git a/requirements.txt b/requirements.txt index aee0842..49e755d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,6 @@ -e . pytest==4.2.0 pytest-flakes==4.0.0 +# because of pip bug https://github.com/pypa/pip/issues/4780 +aiohttp==3.5.4 +certifi==2019.3.9 diff --git a/setup.py b/setup.py index 2aca14b..d50ec98 100644 --- a/setup.py +++ b/setup.py @@ -7,5 +7,9 @@ setup( author='Galaxy team', author_email='galaxy@gog.com', packages=find_packages("src"), - package_dir={'': 'src'} + package_dir={'': 'src'}, + install_requires=[ + "aiohttp==3.5.4", + "certifi==2019.3.9" + ] ) diff --git a/src/galaxy/http.py b/src/galaxy/http.py new file mode 100644 index 0000000..2f984e6 --- /dev/null +++ b/src/galaxy/http.py @@ -0,0 +1,41 @@ +import asyncio +import ssl +from http import HTTPStatus + +import aiohttp +import certifi + +from galaxy.api.errors import ( + AccessDenied, AuthenticationRequired, + BackendTimeout, BackendNotAvailable, BackendError, NetworkError, UnknownError +) + +class AuthenticatedHttpClient: + def __init__(self, limit=20): # TODO timeout? + ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ssl_context.load_verify_locations(certifi.where()) + connector = aiohttp.TCPConnector(limit=limit, ssl=ssl_context) + self._session = aiohttp.ClientSession(connector=connector) + + async def close(self): + await self._session.close() + + async def request(self, method, *args, **kwargs): + try: + response = await self._session.request(method, *args, **kwargs) + except asyncio.TimeoutError: + raise BackendTimeout() + except aiohttp.ClientConnectionError: + raise NetworkError() + if response.status == HTTPStatus.UNAUTHORIZED: + raise AuthenticationRequired() + if response.status == HTTPStatus.FORBIDDEN: + raise AccessDenied() + if response.status == HTTPStatus.SERVICE_UNAVAILABLE: + raise BackendNotAvailable() + if response.status >= 500: + raise BackendError() + if response.status >= 400: + raise UnknownError() + + return response