ratelimit Python Package

repository·master·Indexed 19 days ago

https://github.com/tomasbasham/ratelimit

A Python package providing function decorators to prevent functions from being called more frequently than allowed by API providers. It includes the @limits decorator to restrict calls based on a specified number of invocations and time period, and the @sleep_and_retry decorator to pause execution instead of raising a RateLimitException.

Tokens
865
Snippets
5
Records
5
Agent score
24%

What's inside ratelimit

  1. Handle RateLimitException with retry strategies

    master

    When using @limits, you can catch the ratelimit.RateLimitException to implement custom retry logic, such as exponential backoff using the backoff library.

    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
  2. Use @sleep_and_retry to pause execution instead of raising exceptions

    master

    If you prefer to halt the current thread until the rate limit period has elapsed rather than handling an exception, use the @sleep_and_retry decorator in conjunction with @limits. This ensures every function invocation eventually succeeds, but it blocks 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
  3. Use the @limits decorator to restrict function calls

    master

    The @limits decorator prevents a function from being called more often than allowed by an API provider. It accepts two arguments:

    • calls: The number of allowed invocations.
    • period: The time window in seconds. If not specified, it defaults to 900 seconds (15 minutes).

    If the limit is exceeded, the decorator raises a ratelimit.RateLimitException.

    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