Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- import asyncio
- from collections import deque
- from attr import dataclass, ib
- @dataclass(slots=True, frozen=True)
- class AsyncThrottler:
- rate_limit: int
- period: float
- interval: float = 0.01
- tasks_times: deque = ib(factory=deque, init=False)
- def wait(self) -> None:
- now = time.time()
- while self.tasks_times:
- task_wait_time = now - self.tasks_times[0]
- if task_wait_time > self.period:
- self.tasks_times.popleft()
- continue
- break
- async def acquire(self) -> None:
- while True:
- self.wait()
- if len(self.tasks_times) < self.rate_limit:
- break
- await asyncio.sleep(self.interval)
- self.tasks_times.append(time.time())
- async def __aenter__(self) -> None:
- await self.acquire()
- async def __aexit__(self, exc_type, exc, tb) -> None:
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement