Skip to main content

Add your description here

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(f"Requesting {url}, {rate_keeper}, {rate_keeper.recommend_delay:.2f}")

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

# Output:
# Requesting https://www.example.com/0, RateKeeper(limit=3, period=1, used=1, reset=55981.89), 0.50
# Requesting https://www.example.com/1, RateKeeper(limit=3, period=1, used=2, reset=55981.89), 0.50
# Requesting https://www.example.com/2, RateKeeper(limit=3, period=1, used=1, reset=55982.89), 0.50
# Requesting https://www.example.com/3, RateKeeper(limit=3, period=1, used=2, reset=55982.89), 0.50
# Requesting https://www.example.com/4, RateKeeper(limit=3, period=1, used=1, reset=55983.906), 0.50
# Requesting https://www.example.com/5, RateKeeper(limit=3, period=1, used=2, reset=55983.906), 0.50

Dynamic Adjust

from typing import Dict
import requests
from requests import Response
from datetime import datetime, timezone
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": "Follower Bot",
        "Authorization": f"token {token}",
    }


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

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

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.1.1.tar.gz (4.7 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.1.1-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: rate_keeper-0.1.1.tar.gz
  • Upload date:
  • Size: 4.7 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.1.1.tar.gz
Algorithm Hash digest
SHA256 851e23ce29317c0e6691230af9032f0e66e1b02aa8df978e74cddc544d7d2653
MD5 5a1f580f40d306e2170a3eed57d1e6f3
BLAKE2b-256 75b9fa38f8a1827658196ea06350932bd932d90d6fd3d63b3d055f94c45d737b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: rate_keeper-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 5.0 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.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 9cbed6e2d6b18fedd33a0c13c086cf2c816172936fd949c33bb46bcf1898a009
MD5 0b651a0ee912f3e2c122e590e2e0e0eb
BLAKE2b-256 f0defdd43adb10a89d0c8a7a62d73b7ce3e2ab0427198e6dc3b2dd8bb82be7ae

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