fix limits

This commit is contained in:
user 2024-04-05 22:12:07 +03:00
parent 5149346772
commit dfbc61e46f
1 changed files with 13 additions and 5 deletions

View File

@ -9,11 +9,15 @@ from app.core.logger import make_log
class TonCenter: class TonCenter:
LIMIT_PER_SECOND = 5
def __init__(self, host: str, api_key: str = None, v3_host: str = None, testnet: bool = False): def __init__(self, host: str, api_key: str = None, v3_host: str = None, testnet: bool = False):
self.host = host self.host = host
self.api_key = api_key self.api_key = api_key
self.v3_host = v3_host self.v3_host = v3_host
self.last_used = time.time()
self.reset_timer = time.time()
self.requests_count = 0
async def request(self, method: str, endpoint: str, *args, v3: bool=False, tries_count=0, **kwargs) -> dict: async def request(self, method: str, endpoint: str, *args, v3: bool=False, tries_count=0, **kwargs) -> dict:
if tries_count > 3: if tries_count > 3:
@ -26,11 +30,15 @@ class TonCenter:
kwargs['headers'] = kwargs.get('headers', {}) kwargs['headers'] = kwargs.get('headers', {})
kwargs['headers']['X-API-Key'] = self.api_key kwargs['headers']['X-API-Key'] = self.api_key
if not self.api_key: if self.requests_count >= self.LIMIT_PER_SECOND:
while time.time() < self.last_used + 1.2: while (time.time() - self.reset_timer) < 1.2:
await asyncio.sleep(0.1) await asyncio.sleep(.1)
self.reset_timer = time.time()
self.requests_count = 0
self.requests_count += 1
self.last_used = time.time()
response = await client.request(method, f"{self.v3_host if v3 is True else self.host}{endpoint}", *args, **kwargs) response = await client.request(method, f"{self.v3_host if v3 is True else self.host}{endpoint}", *args, **kwargs)
try: try:
if response.status_code != 200: if response.status_code != 200: