API Reference
API Reference
Quick links:
- pycurb.core.models
- pycurb.core.storage
- pycurb.core.limiter
- pycurb.core.limiter_async
- pycurb.core.resolver
- pycurb.core.decorators
- pycurb.utils
pycurb.core.models¶
pycurb.core.models.LimitRule ¶
Bases: BaseModel
Configuration for a rate limit rule.
Users create an instance of this class to define how requests are limited.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Short unique identifier for the rule. |
algorithm |
Literal['sliding_window', 'fixed_window', 'token_bucket', 'leaky_bucket', 'gcra']
|
Rate limit algorithm to use. |
limit |
Optional[int]
|
Maximum requests allowed (window-based) or capacity (token bucket/gcra). |
window |
Optional[int]
|
Time window in seconds (for window-based algorithms) or base to calculate refill rate. |
capacity |
Optional[int]
|
Maximum capacity for token bucket or gcra (burst limit). |
refill_rate |
Optional[float]
|
Tokens added per second for token bucket or requests allowed per second for GCRA. |
leak_rate |
Optional[float]
|
Requests processed per second. |
metadata |
Dict[str, Any]
|
Arbitrary user data for extra conditional logic. |
Methods:¶
validate_algorithm_parameters ¶
Ensure algorithm-specific parameters are valid.
Source code in src/pycurb/core/models.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
pycurb.core.models.RateLimitResult ¶
Bases: BaseModel
Outcome of a rate limit check.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed |
bool
|
Request permitted or not. |
remaining |
int
|
Remaining requests/tokens in current window/bucket. |
reset_at |
float
|
Unix timestamp (seconds) when the limit resets. |
limit |
int
|
The configured limit (for X-RateLimit-Limit header). |
retry_after |
Optional[int]
|
Seconds to wait before retrying (only when allowed is False). |
rule_name |
Optional[str]
|
Name of the rule that was applied. |
pycurb.core.models.RateLimitHeaders ¶
Bases: BaseModel
Helper to build standard HTTP ratelimit headers.
Attributes:
| Name | Type | Description |
|---|---|---|
limit |
int
|
Value for |
remaining |
int
|
Value for |
reset |
int
|
Value for |
retry_after |
Optional[int]
|
Optional |
Methods:¶
from_result
classmethod
¶
Construct headers from a rate limit result If retry_after is not set, compute as max(0, reset_at - now).
Source code in src/pycurb/core/models.py
to_dict ¶
Convert to dictionary of header names and values
Source code in src/pycurb/core/models.py
pycurb.core.models.RateLimitExceeded ¶
Bases: Exception
Exception raised when rate limit has been exceeded.
Attributes:
| Name | Type | Description |
|---|---|---|
result |
The |
Source code in src/pycurb/core/models.py
pycurb.core.storage¶
pycurb.core.storage.base.Storage ¶
Bases: ABC
Abstract storage backend for rate limiter counters.
Methods:¶
close
abstractmethod
¶
fixed_window
abstractmethod
¶
Record a request using fixed window algorithm.
The window is aligned to calendar boundaries: e.g., window=60 means windows start at timestamps 0, 60, 120, ... (floor(now / window) * window).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
window
|
int
|
Window size in seconds. |
required |
limit
|
int
|
Maximum requests per window. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Tuple (allowed, remaining, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base.py
gcra
abstractmethod
¶
Process a request through Generic Cell Rate Algorithm. It enforces a steady request rate with a defined burst limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
capacity
|
int
|
Maximum burst size (number of requests that can be sent immediately). |
required |
rate
|
float
|
Requests processed per second. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
(allowed, remaining_capacity, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base.py
leaky_bucket
abstractmethod
¶
Process a request through a leaky bucket.
The bucket has a capacity (queue size). Requests leak out at leak_rate per second. If the bucket is full, request is denied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
capacity
|
int
|
Maximum queue size. |
required |
leak_rate
|
float
|
Requests processed per second (leak rate). |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
(allowed, remaining_capacity, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base.py
sliding_window
abstractmethod
¶
Record a request using sliding window algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
window
|
int
|
Time window in seconds. |
required |
limit
|
int
|
Maximum allowed requests per window. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Tuple (allowed, remaining, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base.py
token_bucket
abstractmethod
¶
Consume one token from a token bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
capacity
|
int
|
Maximum tokens (burst limit). |
required |
refill_rate
|
float
|
Tokens added per second. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
(allowed, remaining_tokens, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base.py
pycurb.core.storage.base_async.AsyncStorage ¶
Bases: ABC
Abstract storage backend for rate limiter counters. Asynchronous version (WSGI compatible)
Methods:¶
close
abstractmethod
async
¶
fixed_window
abstractmethod
async
¶
Record a request using fixed window algorithm.
The window is aligned to calendar boundaries: e.g., window=60 means windows start at timestamps 0, 60, 120, ... (floor(now / window) * window).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
window
|
int
|
Window size in seconds. |
required |
limit
|
int
|
Maximum requests per window. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Tuple (allowed, remaining, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base_async.py
gcra
abstractmethod
async
¶
Process a request through Generic Cell Rate Algorithm. It enforces a steady request rate with a defined burst limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
capacity
|
int
|
Maximum burst size (number of requests that can be sent immediately). |
required |
rate
|
float
|
Requests processed per second. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
(allowed, remaining_capacity, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base_async.py
leaky_bucket
abstractmethod
async
¶
Process a request through a leaky bucket.
The bucket has a capacity (queue size). Requests leak out at leak_rate per second. If the bucket is full, request is denied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
capacity
|
int
|
Maximum queue size. |
required |
leak_rate
|
float
|
Requests processed per second (leak rate). |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
(allowed, remaining_capacity, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base_async.py
sliding_window
abstractmethod
async
¶
Record a request using sliding window algorithm.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
window
|
int
|
Time window in seconds. |
required |
limit
|
int
|
Maximum allowed requests per window. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Tuple (allowed, remaining, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base_async.py
token_bucket
abstractmethod
async
¶
Consume one token from a token bucket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Unique identifier. |
required |
capacity
|
int
|
Maximum tokens (burst limit). |
required |
refill_rate
|
float
|
Tokens added per second. |
required |
now
|
float
|
Current Unix timestamp (seconds). |
required |
Returns:
| Type | Description |
|---|---|
bool
|
(allowed, remaining_tokens, reset_at) |
int
|
|
float
|
|
Tuple[bool, int, float]
|
|
Source code in src/pycurb/core/storage/base_async.py
pycurb.core.storage.memory.MemoryStorage ¶
Bases: Storage
In-memory storage for rate limiting.
Source code in src/pycurb/core/storage/memory.py
pycurb.core.storage.memory_async.AsyncMemoryStorage ¶
Bases: AsyncStorage
Async in-memory storage for rate limiting.
Source code in src/pycurb/core/storage/memory_async.py
pycurb.core.storage.redis.RedisStorage ¶
RedisStorage(
redis_client,
key_prefix="ratelimit:",
use_redis_time=False,
fallback_storage=None,
fail_open=False,
)
Bases: Storage
Redis storage for rate limiting.
Source code in src/pycurb/core/storage/redis.py
pycurb.core.storage.redis_async.AsyncRedisStorage ¶
AsyncRedisStorage(
redis_client,
key_prefix="ratelimit:",
use_redis_time=False,
fallback_storage=None,
fail_open=False,
)
Bases: AsyncStorage
Asynchronous redis storage for rate limiting.
Source code in src/pycurb/core/storage/redis_async.py
pycurb.core.limiter¶
pycurb.core.limiter.RateLimiter ¶
Core rate limiter engine.
Initialize the rate limiter
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage
|
Storage
|
A storage backend (e.g MemoryStorage, RedisStorage) |
required |
rules
|
Optional[List[LimitRule]]
|
A list of LimitRule objects. |
None
|
resolver
|
Optional[Callable[[str], LimitRule]]
|
A custom rule resolver instance. |
None
|
Source code in src/pycurb/core/limiter.py
Methods:¶
add_rule ¶
Add or replace a rule
Source code in src/pycurb/core/limiter.py
check ¶
Check if a request with the given key is allowed under the named rule(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A unique identifier for the client (e.g IP, client_id, API key) |
required |
rule_names
|
Union[str, List[str]]
|
The name of the limit rule to apply. Also accepts multiple rules. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RateLimitResult |
RateLimitResult
|
Decision and metadata |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the rule name(s) is unknown or algorithm is not supported. |
Source code in src/pycurb/core/limiter.py
remove_rule ¶
Remove a rule by name
Source code in src/pycurb/core/limiter.py
pycurb.core.limiter.RateLimiter.check ¶
Check if a request with the given key is allowed under the named rule(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A unique identifier for the client (e.g IP, client_id, API key) |
required |
rule_names
|
Union[str, List[str]]
|
The name of the limit rule to apply. Also accepts multiple rules. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RateLimitResult |
RateLimitResult
|
Decision and metadata |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the rule name(s) is unknown or algorithm is not supported. |
Source code in src/pycurb/core/limiter.py
pycurb.core.limiter.RateLimiter.add_rule ¶
Add or replace a rule
Source code in src/pycurb/core/limiter.py
pycurb.core.limiter.RateLimiter.remove_rule ¶
Remove a rule by name
Source code in src/pycurb/core/limiter.py
pycurb.core.limiter_async¶
pycurb.core.limiter_async.AsyncRateLimiter ¶
Async core rate limiter engine
Initialize the rate limiter
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
storage
|
AsyncStorage
|
A storage backend (e.g MemoryStorage, RedisStorage) |
required |
rules
|
Optional[List[LimitRule]]
|
A list of LimitRule objects |
None
|
resolver
|
Optional[Callable[[str], LimitRule]]
|
A rule resolver instance. |
None
|
Source code in src/pycurb/core/limiter_async.py
Methods:¶
add_rule
async
¶
Add or replace a rule
Source code in src/pycurb/core/limiter_async.py
check
async
¶
Check if a request with the given key is allowed under the named rule(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A unique identifier for the client (e.g IP, client_id, API key) |
required |
rule_names
|
Union[str, List[str]]
|
The name of the limit rule to apply. Also accepts multiple rules. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RateLimitResult |
RateLimitResult
|
Decision and metadata |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the rule name(s) is unknown or algorithm is not supported. |
Source code in src/pycurb/core/limiter_async.py
remove_rule
async
¶
Remove a rule by name
Source code in src/pycurb/core/limiter_async.py
pycurb.core.limiter_async.AsyncRateLimiter.check
async
¶
Check if a request with the given key is allowed under the named rule(s).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
A unique identifier for the client (e.g IP, client_id, API key) |
required |
rule_names
|
Union[str, List[str]]
|
The name of the limit rule to apply. Also accepts multiple rules. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
RateLimitResult |
RateLimitResult
|
Decision and metadata |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the rule name(s) is unknown or algorithm is not supported. |
Source code in src/pycurb/core/limiter_async.py
pycurb.core.resolver¶
pycurb.core.resolver.RuleResolver ¶
pycurb.core.resolver.AsyncRuleResolver ¶
pycurb.core.decorators¶
pycurb.core.decorators.rate_limit ¶
rate_limit(
limiter,
*,
rule_name=None,
limit_str=None,
algorithm="sliding_window",
key_extractor,
)
Unified decorator for rate limiting (both async and sync).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limiter
|
Union[RateLimiter, AsyncRateLimiter]
|
RateLimiter (async) or RateLimiterSync (sync) instance. |
required |
rule_name
|
Optional[Union[str, List[str]]]
|
Name of an existing rule in the limiter's resolver. Also accepts a list of names. |
None
|
limit_str
|
Optional[str]
|
Shorthand string (e.g., "100/s") to create a new rule. |
None
|
algorithm
|
str
|
Algorithm to use when creating a rule from limit_str. |
'sliding_window'
|
key_extractor
|
Optional[Callable[..., str]]
|
Function extracting key (unique identifier) from function arguments. |
required |
Raises:
| Type | Description |
|---|---|
RateLimitExceeded
|
If rate limit has been exceeded. |
Exactly one of rule_name or limit_str must be provided.
Source code in src/pycurb/core/decorators.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
pycurb.core.decorators.arg_extractor ¶
Helper to create a key extractor that combines values of specified argument names. Arguments must be passed as keyword arguments; positional arguments are ignored.
Example
Source code in src/pycurb/core/decorators.py
pycurb.utils¶
pycurb.utils.parse_rate_limit_string ¶
Parse a shorthand rate limit string into (limit, window_seconds).
Supported formats (examples):
- Single number (per-second):
100-> limit=100, window=1 - Per-unit shorthand:
100/s-> limit=100, window=1 - Explicit duration with unit:
100/30s-> limit=100, window=30 - Numeric window without unit:
100/60-> limit=100, window=60 - Larger units:
5/m-> limit=5, window=60;10/h-> limit=10, window=3600
Examples::
```
100/s
100/30s
5/m
5/2m
10/h
10/2h
2/d
2/2d
100
100/60
```
Raises:
| Type | Description |
|---|---|
ValueError
|
if format is invalid. |
Source code in src/pycurb/utils.py
pycurb.utils.parse_duration ¶
Convert a shorthand duration string into seconds. Duration must be an integer followed by a unit. Supported units: - s: seconds - m: minutes - h: hours - d: days
Examples:
parse_duration("30s") -> 30 parse_duration("5m") -> 300 parse_duration("2h") -> 7200 parse_duration("1d") -> 86400
Raises:
| Type | Description |
|---|---|
ValueError
|
If the format is invalid or unit is unsupported. |