asyncio-throttle

1.0.2 · active · verified Sat Apr 11

asyncio-throttle is a simple, easy-to-use library providing a throttler for asynchronous operations in Python. It's designed to limit the rate at which code blocks can be executed, primarily through an `async with` statement. The current stable version is 1.0.2, released in April 2021. It requires Python 3.6 or later.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `Throttler` as an asynchronous context manager to limit the rate of operations across multiple concurrent tasks. It creates five workers that each attempt to print a message, but the `Throttler` ensures a maximum of 5 messages are printed per second in total.

import asyncio
import time
import random
from asyncio_throttle import Throttler

async def worker(no, throttler, n):
    for _ in range(n):
        # Simulate some async work before acquiring the throttle
        await asyncio.sleep(random.random() * 0.5)
        async with throttler:
            # This block will be rate-limited
            print(f'{time.time():.4f} Worker #{no}: Bang!')

async def main():
    # Limit to 5 'Bang!' messages per second across all workers
    throttler = Throttler(rate_limit=5)
    
    # Create 5 workers, each trying to 'Bang!' 3 times
    tasks = [
        asyncio.create_task(worker(no, throttler, 3))
        for no in range(5)
    ]
    await asyncio.gather(*tasks)

if __name__ == '__main__':
    # Ensure to run in an event loop
    asyncio.run(main())

view raw JSON →