Skip to main content

ratelimit build Maintainability Test Coverage

This project is a fork of tomasbasham/ratelimit that implements a sliding log for correctness and provides persistance via sqlite. See the usage section on Persistence for more details. Turning on persistence is highly recommended, especially during development, to ensure rate limits are respected between application restarts.

APIs are a very common way to interact with web services. As the need to consume data grows, so does the number of API calls necessary to remain up to date with data sources. However many API providers constrain developers from making too many API calls. This is know as rate limiting and in a worst case scenario your application can be banned from making further API calls if it abuses these limits.

This packages introduces a function decorator preventing a function from being called more often than that allowed by the API provider. This should prevent API providers from banning your applications by conforming to their rate limits.

Installation

PyPi

Add this line to your application’s requirements.txt:

deckar01-ratelimit

And then execute:

$ pip install -r requirements.txt

Or install it yourself:

$ pip install deckar01-ratelimit

GitHub

Installing the latest version from Github:

$ git clone https://github.com/deckar01/ratelimit
$ cd ratelimit
$ python setup.py install

Usage

To use this package simply decorate any function that makes an API call:

from ratelimit import limits

import requests

FIFTEEN_MINUTES = 900

@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('API response: {}'.format(response.status_code))
    return response

This function will not be able to make more then 15 API call within a 15 minute time period.

The arguments passed into the decorator describe the number of function invocation allowed over a specified time period (in seconds). If no time period is specified then it defaults to 15 minutes (the time window imposed by Twitter).

If a decorated function is called more times than that allowed within the specified time period then a ratelimit.RateLimitException is raised. This may be used to implement a retry strategy such as an expoential backoff

from ratelimit import limits, RateLimitException
from backoff import on_exception, expo

import requests

FIFTEEN_MINUTES = 900

@on_exception(expo, RateLimitException, max_tries=8)
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('API response: {}'.format(response.status_code))
    return response

Alternatively to cause the current thread to sleep until the specified time period has ellapsed and then retry the function use the sleep_and_retry decorator. This ensures that every function invocation is successful at the cost of halting the thread.

from ratelimit import limits, sleep_and_retry

import requests

FIFTEEN_MINUTES = 900

@sleep_and_retry
@limits(calls=15, period=FIFTEEN_MINUTES)
def call_api(url):
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('API response: {}'.format(response.status_code))
    return response

Persistence

If a limit needs to be respected between application restarts or shared by multiple processes, the storage argument can be used to save the limit state to disk and load it automatically.

from ratelimit import limits, sleep_and_retry

import requests

FIFTEEN_MINUTES = 900

@sleep_and_retry
@limits(calls=15, period=FIFTEEN_MINUTES, storage='ratelimit.db')
def call_api(url):
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('API response: {}'.format(response.status_code))
    return response

If multiple limits need to be persisted, the name argument can be used to store them in the same database using different tables.

from ratelimit import limits, sleep_and_retry

import requests

HOUR = 3600
DAY = 24*HOUR

@sleep_and_retry
@limits(calls=15, period=HOUR, storage='ratelimit.db', name='hourly_limit')
@sleep_and_retry
@limits(calls=100, period=DAY, storage='ratelimit.db', name='daily_limit')
def call_api(url):
    response = requests.get(url)

    if response.status_code != 200:
        raise Exception('API response: {}'.format(response.status_code))
    return response

License

This project is licensed under the MIT License.

Metadata

Release files for deckar01-ratelimit 3.0.2

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

Source distribution (sdist)

Source distribution for deckar01-ratelimit 3.0.2
File Size Uploaded Provenance
deckar01-ratelimit-3.0.2.tar.gz 7.9 kB Without provenance Details

Built distributions (wheels)

Table of built distributions (wheels) for deckar01-ratelimit 3.0.2
File Interpreter ABI Platform
deckar01_ratelimit-3.0.2-py3-none-any.whl Python 3 none any Details
deckar01_ratelimit-3.0.2-py2-none-any.whl Python 2 none any Details

Total release size: 21.7 kB

Release files / deckar01-ratelimit-3.0.2.tar.gz

Download URL deckar01-ratelimit-3.0.2.tar.gz
Size 7.9 kB
Tags Source
SHA-256 checksum
How to use checksums
6f3f16f908c8e56bde66bb57e4491971e61b509e9ee8ac721354bc1a3c518dd5
BLAKE2b-256 checksum
How to use checksums
4d78f005bb3b66152a60d590c1c939692431cea54bfc6dd91d10f5c5dd218583
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

Release files / deckar01_ratelimit-3.0.2-py3-none-any.whl

Download URL deckar01_ratelimit-3.0.2-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c29bd1e03d768754a528622c5b6538ac0ae3ef8c0e76415e8a7125ae715852cd
BLAKE2b-256 checksum
How to use checksums
fe1aa2a270f038ea23336cffb0d274904a822585c0a7de5c5e60cdaada2a05f4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

Release files / deckar01_ratelimit-3.0.2-py2-none-any.whl

Download URL deckar01_ratelimit-3.0.2-py2-none-any.whl
Size 6.9 kB
Tags Python 2
SHA-256 checksum
How to use checksums
5de6341ccc2198cf1179c37d372313611dcd671765b3305b7c0340eb52c7549b
BLAKE2b-256 checksum
How to use checksums
8245a0d5bfcd8ce26bf6cea60df85c813dc596d4e42d99ec2739c7a502abeeb0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.6.0 importlib_metadata/4.8.2 pkginfo/1.8.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.10.0

Security for deckar01-ratelimit 3.0.2

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.

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