pferd/PFERD/limiter.py

20 lines
540 B
Python
Raw Normal View History

2021-04-29 10:24:28 +02:00
import asyncio
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from typing import AsyncIterator
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()
def limit(self) -> AbstractAsyncContextManager[None]:
return self._context_manager()