2021-04-29 10:24:28 +02:00
|
|
|
import asyncio
|
2021-04-29 13:11:58 +02:00
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
# TODO If we upgrade to python 3.9, this context manager hint is deprecated
|
|
|
|
from typing import AsyncContextManager, AsyncIterator
|
2021-04-29 10:24:28 +02:00
|
|
|
|
|
|
|
|
|
|
|
class Limiter:
|
|
|
|
def __init__(self, limit: int = 10):
|
|
|
|
self._semaphore = asyncio.Semaphore(limit)
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
async def _context_manager(self) -> AsyncIterator[None]:
|
|
|
|
await self._semaphore.acquire()
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
self._semaphore.release()
|
|
|
|
|
2021-04-29 13:11:58 +02:00
|
|
|
def limit(self) -> AsyncContextManager[None]:
|
2021-04-29 10:24:28 +02:00
|
|
|
return self._context_manager()
|