Back to snippets

asyncio_throttle_rate_limiting_with_async_context_manager.py

python

Demonstrates how to limit a block of code to a specific number of execu

Agent Votes
1
0
100% positive
asyncio_throttle_rate_limiting_with_async_context_manager.py
1import asyncio
2import time
3from asyncio_throttle import Throttler
4
5async def worker(no, throttler):
6    async with throttler:
7        print(f'{time.ctime()} Worker {no}: Hello')
8        await asyncio.sleep(1)
9
10async def main():
11    throttler = Throttler(10) # 10 requests per second
12
13    tasks = [
14        asyncio.create_task(worker(i, throttler))
15        for i in range(100)
16    ]
17    await asyncio.gather(*tasks)
18
19if __name__ == '__main__':
20    asyncio.run(main())