Skip to main content

A lightweight package that provides rate-limited httpx transports.

Project description

HTTPX Limiter

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

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.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.

Rate.create(magnitude=1, duration=1/20)

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(),
    ),
)

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

from datetime import datetime, timezone
from collections.abc import Sequence

import httpx
from httpx_limiter import AbstractRateLimiterRepository, 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_rates(self, _: httpx.Request) -> Sequence[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.4.0.tar.gz (13.6 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.4.0-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: httpx_limiter-0.4.0.tar.gz
  • Upload date:
  • Size: 13.6 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.4.0.tar.gz
Algorithm Hash digest
SHA256 b1c6a39f4bad7654fdd934da1e0119cd91e9bd2ad61b9adad623cd7081c1a3b7
MD5 ca356dd22cec65617498e3ba53843b31
BLAKE2b-256 368d77c18a5d147e0e8ddc6fe124d9e48ea43e52ba9f7c91a5ab49e4909550f5

See more details on using hashes here.

Provenance

The following attestation bundles were made for httpx_limiter-0.4.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.4.0-py3-none-any.whl.

File metadata

  • Download URL: httpx_limiter-0.4.0-py3-none-any.whl
  • Upload date:
  • Size: 16.0 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.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 33d914c442bce14fc1d8f28e0a954c87d9f5f5a82b51a6778f1f1a3506d9e6ac
MD5 c32d000b4b7d503c90954ea9226b0e79
BLAKE2b-256 2394b2d08aaadd219313d4ec8c843a53643779815c2ef06e8982f79acc57f1d2

See more details on using hashes here.

Provenance

The following attestation bundles were made for httpx_limiter-0.4.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