Skip to main content

AsyncRateLimiter

AsyncIO-enabled rate limiter - limit the rate of API calls!

Public APIs such as Wiktionary may apply rate limits at which one may call any part of their API. A generous API will inform you of this rate limit through a well structured error. Other cases, however, may not be so graceous. It may respond with a general purpose status code 500; a generic, non-informative HTML error page; or even outright close the connection lacking any response whatsoever. For these cases, a rate limiter can help avoid triggering such a response altogether.

AsyncRateLimiter is partly inspired by ratelimiter. The main difference is that AsyncRateLimiter is designed for asynchronous usage, whereas ratelimiter is designed for sequential API calls - further wrap-around code is needed to enable asynchronous code. AsyncRateLimiter integrates with AsyncIO for convenience.

Installation

Simply install via pip install asyncratelimiter

Dependencies

There is a single dependency for convenience: requests

Styles

AsyncRateLimiter supports two distinct usage styles:

  1. Threaded style - incorporates sequential APIs such as requests with rate-limited AsyncIO
  2. Async style - limits calls to AsyncIO-based APIs

Threaded Style

Threaded style revolves around the ThreadedRateLimiter.dispatch(fun, /, *args, **kwargs) method. fun is enqueued with Python's standard concurrent.futures.ThreadPoolExecutor, which is particularly useful to dispatch multiple I/O-dependent tasks and waiting on their completion simultaneously.

from asyncratelimiter import ThreadedRateLimiter
import asyncio

async def main():
    with ThreadedRateLimiter(max_rate=10, interval=1) as limiter:
        futures = []
        for _ in range(100):
            futures.append(limiter.dispatch())
asyncio.run(main())

Requests Integration

A simple derivation of ThreadedRateLimiter exposing get, post, put, delete, and request methods; one may still access ThreadedRateLimiter.dispatch as normal.

from asyncratelimiter import RequestLimiter
import asyncio

async def main():
    futures = []
    with RequestLimiter(max_rate=10, interval=2) as requests:
        for _ in range(100):
            futures.append(requests.get('https://google.com'))
        await asyncio.gather(*futures)
        # Should take ~18-20 seconds - the last batch need not necessarily take the full 2s interval
asyncio.run(main())

Async Style

Async style behaves much like ratelimiter, except AsyncIO-integrated.

from asyncratelimiter import AsyncRateLimiter
import asyncio

async def foo():
    return 42

async def main():
    ratelimiter = AsyncRateLimiter(max_rate=10, interval=1)
    for _ in range(100):
        async with ratelimiter:
            await foo()
asyncio.run(main())

For concurrently running tasks, async style still exposes a dispatch(aw: Awaitable) method:

from asyncratelimiter import AsyncRateLimiter
import asyncio

async def foo(delay: float):
    await asyncio.sleep(delay)
    return 42

async def main():
    ratelimiter = AsyncRateLimiter(max_rate=10, interval=1)
    aws = []
    for _ in range(100):
        aws.append(ratelimiter.dispatch(foo(0.5)))
    await asyncio.gatcher(*aws)

License

MIT License

Copyright (c) 2021 Kiruse

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Metadata

Release files for asyncratelimiter 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for asyncratelimiter 1.0.0
File Size Uploaded Provenance Actions
asyncratelimiter-1.0.0.tar.gz 5.8 kB Without provenance Details for asyncratelimiter-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for asyncratelimiter 1.0.0
File Interpreter ABI Platform Actions
asyncratelimiter-1.0.0-py3-none-any.whl Python 3 none any Details for asyncratelimiter-1.0.0-py3-none-any.whl

Total release size: 11.5 kB

Release files / asyncratelimiter-1.0.0.tar.gz

Download URL asyncratelimiter-1.0.0.tar.gz
Size 5.8 kB
Tags Source
SHA-256 checksum
How to use checksums
b9e57d1a5f4281353cbaa59381bae72118e58b621f1982917d16dede3dd49f59
BLAKE2b-256 checksum
How to use checksums
83feaca69a09973ef3fa56efec3c91d13ef8a3fb56fb6abf139d7c92fab0c82b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.6.1 requests/2.25.1 setuptools/56.0.0 requests-toolbelt/0.9.1 tqdm/4.54.1 CPython/3.9.5

Release files / asyncratelimiter-1.0.0-py3-none-any.whl

Download URL asyncratelimiter-1.0.0-py3-none-any.whl
Size 5.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b22e80110bae6c959f770ee1daf1627e1fe7bdfe9d66953dc937aeac67f2b048
BLAKE2b-256 checksum
How to use checksums
a922a8208925695f8161029c8dcd8b01b20de9607332d588a962d3b5b2cbd8ef
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.2.0 pkginfo/1.6.1 requests/2.25.1 setuptools/56.0.0 requests-toolbelt/0.9.1 tqdm/4.54.1 CPython/3.9.5

Security for asyncratelimiter 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page