Add HttpClient

This commit is contained in:
Romuald Juchnowicz-Bierbasz
2019-05-10 13:36:32 +02:00
parent 90835ece58
commit 234a21d085
3 changed files with 49 additions and 1 deletions

View File

@@ -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

View File

@@ -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"
]
)

41
src/galaxy/http.py Normal file
View File

@@ -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