From b915e393dd28a3fe317eb552f211e9c0c0738a35 Mon Sep 17 00:00:00 2001 From: Joscha Date: Thu, 29 Apr 2021 10:24:28 +0200 Subject: [PATCH] Implement limiter --- PFERD/limiter.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 PFERD/limiter.py diff --git a/PFERD/limiter.py b/PFERD/limiter.py new file mode 100644 index 0000000..f73e2cd --- /dev/null +++ b/PFERD/limiter.py @@ -0,0 +1,19 @@ +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()