File size: 1,764 Bytes
1c6c5d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from typing import Dict, Optional, Any
import json

import aiohttp


class BaseAsyncAPI:

    def __init__(self, url: str, headers: Optional[Dict[str, Any]] = None, retries: int = 3) -> None:
        self.__url = url
        self.__headers = headers
        self.__retries = max(retries, 5)

    async def get(self, **request_kwargs):
        session_timeout = aiohttp.ClientTimeout(total=30)
        async with aiohttp.ClientSession(headers=self.__headers, timeout=session_timeout) as session:
            output = {}
            count = 1
            while True:
                if count >= self.__retries:
                    break
                async with session.get(url=self.__url, params=request_kwargs) as r:
                    if r.status in {429, 500, 502, 503, 504}:
                        count += 1
                    elif r.status == 200:
                        output = await r.json()
                        break
                    else:
                        break
        return output

    async def post(self, payload: Dict[str, Any]):
        session_timeout = aiohttp.ClientTimeout(total=30)
        async with aiohttp.ClientSession(headers=self.__headers, timeout=session_timeout) as session:
            output = {}
            count = 1
            while True:
                if count >= self.__retries:
                    break
                async with session.post(url=self.__url, data=json.dumps(payload).encode('utf8')) as r:
                    if r.status in {429, 500, 502, 503, 504}:
                        count += 1
                    elif r.status == 200:
                        output = await r.json()
                        break
                    else:
                        break
        return output