Skip to main content

A lightweight package that provides rate-limited httpx transports.

Project description

HTTPX Limiter

Package Latest PyPI Version Supported Python Versions Documentation
Meta Apache-2.0 Code of Conduct Checked with mypy Code Style Black Linting: Ruff
Automation

A lightweight package that provides rate-limited httpx transports.

Installation

The package is published on PyPI. Install it, for example, with

pip install httpx-limiter

Tutorial

You can limit the number of requests made by an HTTPX client using the transports provided in this package. That is useful in situations when you need to make a large number of asynchronous requests against endpoints that implement a rate limit,

Single Rate Limit

The simplest use case is to apply a single rate limit to all requests. If you want to be able to make twenty requests per second, for example, use the following code:

import httpx
from httpx_limiter import AsyncRateLimitedTransport, Rate

async def main():
    async with httpx.AsyncClient(
        transport=AsyncRateLimitedTransport.create(rate=Rate.create(magnitude=20)),
    ) as client:
        response = await client.get("https://httpbin.org")

[!IMPORTANT] Due to limitations in the design of the underlying leaky bucket implementation, which is used to implement the rate limiting, the magnitude of the rate is also the maximum capacity of the bucket. That means, if you set a rate that is larger than one, a burst of requests equal to that capacity will be allowed. If you do not want to allow any bursts, set the magnitude to one, but the duration to the inverse of your desired rate. If you want to allow twenty requests per second, for example, set the magnitude to 1 and the duration to 0.05 seconds.

Multiple Rate Limits

For more advanced use cases, you can apply different rate limits based on a concrete implementation of the AbstractRateLimiterRepository. There are two relevant methods that both get passed the current request. One method needs to identify which rate limit to apply, and the other method sets the rate limit itself. See the following example:

import httpx
from httpx_limiter import AbstractRateLimiterRepository, AsyncMultiRateLimitedTransport, Rate

class DomainBasedRateLimiterRepository(AbstractRateLimiterRepository):
    """Apply different rate limits based on the domain being requested."""
    
    def get_identifier(self, request: httpx.Request) -> str:
        """Return the domain as the identifier for rate limiting."""
        return request.url.host
    
    def get_rate(self, request: httpx.Request) -> Rate:
        """Apply the same, but independent rate limit to each domain."""
        return Rate.create(magnitude=25)

client = httpx.AsyncClient(
    transport=AsyncMultiRateLimitedTransport.create(
        repository=DomainBasedRateLimiterRepository(),
    ),
)

[!NOTE] You are free to ignore the request argument and use global information like the time of day to determine the rate limit.

from datetime import datetime, timezone

import httpx
from httpx_limiter import AbstractRateLimiterRepository, AsyncMultiRateLimitedTransport, Rate

class DayNightRateLimiterRepository(AbstractRateLimiterRepository):
    """Apply different rate limits based on the time of day."""

    def get_identifier(self, _: httpx.Request) -> str:
        """Identify whether it is currently day or night."""
        if 6 <= datetime.now(tz=timezone.utc).hour < 18:
            return "day"
        
        return "night"

    def get_rate(self, _: httpx.Request) -> Rate:
        """Apply different rate limits during the day or night."""
        if self.get_identifier(_) == "day":
            return Rate.create(magnitude=10)
        
        return Rate.create(magnitude=100)

Copyright

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

httpx_limiter-0.3.0.tar.gz (11.9 kB view details)

Uploaded Source

Built Distribution

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

httpx_limiter-0.3.0-py3-none-any.whl (12.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: httpx_limiter-0.3.0.tar.gz
  • Upload date:
  • Size: 11.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for httpx_limiter-0.3.0.tar.gz
Algorithm Hash digest
SHA256 4d0c422edc40d41f882e94718466cbe91d3877097afe67bd3f55a9c0df3ea321
MD5 fbfa5fc550f290b210bc7f59fe13caa4
BLAKE2b-256 6f72b8ef470dca30babce55fd9e59756b682999c757417adaf0ee99d846e5705

See more details on using hashes here.

Provenance

The following attestation bundles were made for httpx_limiter-0.3.0.tar.gz:

Publisher: release.yml on Midnighter/httpx-limiter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

  • Download URL: httpx_limiter-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 12.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for httpx_limiter-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 69f6e350456d2fe6eea5a36508098a925df16ef15e3d96d4abddd73fa0017625
MD5 9fd04fa24db1aeeb94563808a5c88cc3
BLAKE2b-256 0ff6a71ea5bef3aa9bb34ef6e3b017b40616ceccb60621b234112be39d6fbc79

See more details on using hashes here.

Provenance

The following attestation bundles were made for httpx_limiter-0.3.0-py3-none-any.whl:

Publisher: release.yml on Midnighter/httpx-limiter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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