-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Dor Amram
committed
Jan 9, 2020
1 parent
2d561cd
commit 7f3e6db
Showing
4 changed files
with
61 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import aiohttp | ||
import asyncio | ||
import logging | ||
import yarl | ||
from aiohttp import ClientSession | ||
from typing import Optional, Dict, Any | ||
from tenacity import stop_after_attempt, stop_after_delay, retry | ||
from .exc import HTTPError | ||
|
||
|
||
logger = logging.getLogger("scotty") # type: logging.Logger | ||
|
||
|
||
class AsyncRequestHelper: | ||
def __init__(self): | ||
self._loop = asyncio.get_event_loop() | ||
self._session = aiohttp.ClientSession( | ||
loop=self._loop, timeout=aiohttp.ClientTimeout(total=30), | ||
headers={"Accept-Encoding": "gzip", 'Content-Type': 'application/json'} | ||
) | ||
|
||
@retry(stop=(stop_after_delay(5) | stop_after_attempt(3))) | ||
async def execute_http( | ||
self, url: yarl.URL, *, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, | ||
) -> Dict[str, Any]: | ||
method = "GET" if data is None else "POST" | ||
logger.info("Async Calling {} {}", method, url) | ||
async with self._session.request(method, url, params=params, json=data) as response: | ||
if response.status != 200: | ||
raise HTTPError(url=url, code=response.status, text=await response.text()) | ||
return await response.json() | ||
|
||
def __del__(self): | ||
self._loop.run_until_complete(self._session.close()) | ||
|
||
|
||
_async_request_helper = AsyncRequestHelper() | ||
execute_http = _async_request_helper.execute_http |