Skip to main content

Used to limit function call frequency. It ensures your function is called evenly within the limit rather than being called intensively in a short time.

Project description

badge-collection

Rate Keeper

中文 | English

Rate Keeper: Used to limit function call frequency. It ensures your function is called evenly within the limit rather than being called intensively in a short time. Moreover, it can dynamically adjust the call frequency based on remaining calls and time.

Installation

pip install rate-keeper

Quick Start

from rate_keeper import RateKeeper

if __name__ == "__main__":
    rate_keeper = RateKeeper(limit=3, period=1)

    @rate_keeper.decorator
    def request(url: str) -> str:
        print(url, rate_keeper, f"{rate_keeper.delay_time:.2f}")

    count = 0
    while count < 6:
        request(f"https://www.example.com/{count}")
        count += 1

# Output:
# https://www.example.com/0 RateKeeper(limit=3, period=1, used=1, reset=89614.39) 0.00
# https://www.example.com/1 RateKeeper(limit=3, period=1, used=2, reset=89614.39) 0.50
# https://www.example.com/2 RateKeeper(limit=3, period=1, used=1, reset=89615.406) 0.48
# https://www.example.com/3 RateKeeper(limit=3, period=1, used=2, reset=89615.406) 0.50
# https://www.example.com/4 RateKeeper(limit=3, period=1, used=1, reset=89616.421) 0.49
# https://www.example.com/5 RateKeeper(limit=3, period=1, used=2, reset=89616.421) 0.50

Dynamic Adjust

from datetime import datetime, timezone
from typing import Dict

import requests
from requests import Response

from rate_keeper import RateKeeper

timestamp_clock = datetime.now(timezone.utc).timestamp
rate_keeper = RateKeeper(limit=5000, period=3600, clock=timestamp_clock)


@rate_keeper.decorator
def fetch(
    method: str, url: str, headers: Dict[str, str] = {}, params: Dict[str, str] = {}
) -> Response:
    # https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#checking-the-status-of-your-rate-limit
    response = requests.request(method, url, headers=headers, params=params)

    headers_map = {
        "x-ratelimit-limit": rate_keeper.update_limit,
        "x-ratelimit-used": rate_keeper.update_used,
        "x-ratelimit-reset": rate_keeper.update_reset,
    }

    for key, value in response.headers.items():
        lower_key = key.lower()
        if lower_key in headers_map:
            headers_map[lower_key](int(value))

    return response


def create_headers(token: str) -> Dict[str, str]:
    return {
        "Accept": "application/vnd.github.v3+json",
        "User-Agent": "Python requests GitHub API",
        "Authorization": f"token {token}",
    }


print(rate_keeper, f"{rate_keeper.recommend_delay:.2f}")
response = fetch("GET", "https://api.github.com/user", create_headers("github_token"))
print(response.json())
print(rate_keeper, f"{rate_keeper.recommend_delay:.2f}")

# Output:
# RateKeeper(limit=5000, period=3600, used=0, reset=1745897378.901664) 0.00
# {'message': 'Bad credentials', 'documentation_url': 'https://docs.github.com/rest', 'status': '401'}
# RateKeeper(limit=60, period=3600, used=3, reset=1745896988) 56.30

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

rate_keeper-0.3.0.tar.gz (4.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

rate_keeper-0.3.0-py3-none-any.whl (5.3 kB view details)

Uploaded Python 3

File details

Details for the file rate_keeper-0.3.0.tar.gz.

File metadata

  • Download URL: rate_keeper-0.3.0.tar.gz
  • Upload date:
  • Size: 4.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.9

File hashes

Hashes for rate_keeper-0.3.0.tar.gz
Algorithm Hash digest
SHA256 830b6eeff5454bd69cc633abbd6c8be159852979cd266f541b071c282ad29f1f
MD5 d9926164da92e01a553b24e2b33eb267
BLAKE2b-256 caf28a6121c32e31c31e5aea4ae83ff99c6d9c9e632fc903ae0d9eb419f426b7

See more details on using hashes here.

File details

Details for the file rate_keeper-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: rate_keeper-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 5.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.9

File hashes

Hashes for rate_keeper-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 06b40c65611285dd479aefac697952bd03900da73371ffd014442d40818ce3ef
MD5 43e1dbb59bec144cba6b27a742af053a
BLAKE2b-256 dac2c9323c570d4bef3ac77d4fc48bb13a0cdead97faa55355db1d6ea8dee698

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page