API#
Extension#
- class Limiter(key_func: Callable[[], str], *, app: Flask | None = None, default_limits: List[str | Callable[[], str]] | None = None, default_limits_per_method: bool | None = None, default_limits_exempt_when: Callable[[], bool] | None = None, default_limits_deduct_when: Callable[[Response], bool] | None = None, default_limits_cost: int | Callable[[], int] | None = None, application_limits: List[str | Callable[[], str]] | None = None, application_limits_cost: int | Callable[[], int] | None = None, headers_enabled: bool | None = None, header_name_mapping: Dict[HeaderNames, str] | None = None, strategy: str | None = None, storage_uri: str | None = None, storage_options: Dict[str, str | int] | None = None, auto_check: bool = True, swallow_errors: bool | None = None, fail_on_first_breach: bool | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, in_memory_fallback: List[str] | None = None, in_memory_fallback_enabled: bool | None = None, retry_after: str | None = None, key_prefix: str = '', request_identifier: Callable[[...], str] | None = None, enabled: bool = True)[source]#
The
Limiter
class initializes the Flask-Limiter extension.- Parameters:
key_func¶ – a callable that returns the domain to rate limit by.
app¶ –
flask.Flask
instance to initialize the extension with.default_limits¶ – a variable list of strings or callables returning strings denoting default limits to apply to all routes that are not explicitely decorated with a limit. Rate limit string notation for more details.
default_limits_per_method¶ – whether default limits are applied per method, per route or as a combination of all method per route.
default_limits_exempt_when¶ – a function that should return True/False to decide if the default limits should be skipped
default_limits_deduct_when¶ – a function that receives the current
flask.Response
object and returns True/False to decide if a deduction should be made from the default rate limit(s)default_limits_cost¶ – The cost of a hit to the default limits as an integer or a function that takes no parameters and returns an integer (Default:
1
).application_limits¶ – a variable list of strings or callables returning strings for limits that are applied to the entire application (i.e a shared limit for all routes)
application_limits_cost¶ – The cost of a hit to the global application limits as an integer or a function that takes no parameters and returns an integer (Default:
1
).headers_enabled¶ – whether
X-RateLimit
response headers are written.header_name_mapping¶ – Mapping of header names to use if
Limiter.headers_enabled
isTrue
. If no mapping is provided the default values will be used.strategy¶ – the strategy to use. Refer to Rate limiting strategies
storage_uri¶ – the storage location. Refer to
RATELIMIT_STORAGE_URI
storage_options¶ – kwargs to pass to the storage implementation upon instantiation.
auto_check¶ – whether to automatically check the rate limit in the before_request chain of the application. default
True
swallow_errors¶ – whether to swallow any errors when hitting a rate limit. An exception will still be logged. default
False
fail_on_first_breach¶ – whether to stop processing remaining limits after the first breach. default
True
on_breach¶ – a function that will be called when any limit in this extension is breached. If the function returns an instance of
flask.Response
that will be the response embedded into theRateLimitExceeded
exception raised.in_memory_fallback¶ – a variable list of strings or callables returning strings denoting fallback limits to apply when the storage is down.
in_memory_fallback_enabled¶ – fall back to in memory storage when the main storage is down and inherits the original limits. default
False
retry_after¶ – Allows configuration of how the value of the Retry-After header is rendered. One of http-date or delta-seconds.
key_prefix¶ – prefix prepended to rate limiter keys and app context global names.
request_identifier¶ – a callable that returns the unique identity the current request. Defaults to
flask.Request.endpoint
enabled¶ – Whether the extension is enabled or not
- limit(limit_value: str | Callable[[], str], *, key_func: Callable[[], str] | None = None, per_method: bool = False, methods: List[str] | None = None, error_message: str | None = None, exempt_when: Callable[[], bool] | None = None, override_defaults: bool = True, deduct_when: Callable[[Response], bool] | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, cost: int | Callable[[], int] = 1, scope: str | Callable[[str], str] | None = None) LimitDecorator [source]#
Decorator to be used for rate limiting individual routes or blueprints.
- Parameters:
limit_value¶ – rate limit string or a callable that returns a string. Rate limit string notation for more details.
key_func¶ – function/lambda to extract the unique identifier for the rate limit. defaults to remote address of the request.
per_method¶ – whether the limit is sub categorized into the http method of the request.
methods¶ – if specified, only the methods in this list will be rate limited (default:
None
).error_message¶ – string (or callable that returns one) to override the error message used in the response.
exempt_when¶ – function/lambda used to decide if the rate limit should skipped.
override_defaults¶ –
whether the decorated limit overrides the default limits (Default:
True
).Note
When used with a
Blueprint
the meaning of the parameter extends to any parents the blueprint instance is registered under. For more details see Nested Blueprintsdeduct_when¶ – a function that receives the current
flask.Response
object and returns True/False to decide if a deduction should be done from the rate limiton_breach¶ – a function that will be called when this limit is breached. If the function returns an instance of
flask.Response
that will be the response embedded into theRateLimitExceeded
exception raised.cost¶ – The cost of a hit or a function that takes no parameters and returns the cost as an integer (Default:
1
).scope¶ – a string or callable that returns a string for further categorizing the rate limiting scope. This scope is combined with the current endpoint of the request.
- Changes
New in version 2.9.0: The returned object can also be used as a context manager
for rate limiting a code block inside a view. For example:
@app.route("/") def route(): try: with limiter.limit("10/second"): # something expensive except RateLimitExceeded: pass
decorator to be applied to multiple routes sharing the same rate limit.
- Parameters:
limit_value¶ – rate limit string or a callable that returns a string. Rate limit string notation for more details.
scope¶ – a string or callable that returns a string for defining the rate limiting scope.
key_func¶ – function/lambda to extract the unique identifier for the rate limit. defaults to remote address of the request.
per_method¶ – whether the limit is sub categorized into the http method of the request.
methods¶ – if specified, only the methods in this list will be rate limited (default:
None
).error_message¶ – string (or callable that returns one) to override the error message used in the response.
exempt_when¶ (function) – function/lambda used to decide if the rate limit should skipped.
override_defaults¶ –
whether the decorated limit overrides the default limits. (default:
True
)Note
When used with a
Blueprint
the meaning of the parameter extends to any parents the blueprint instance is registered under. For more details see Nested Blueprintsdeduct_when¶ – a function that receives the current
flask.Response
object and returns True/False to decide if a deduction should be done from the rate limiton_breach¶ – a function that will be called when this limit is breached. If the function returns an instance of
flask.Response
that will be the response embedded into theRateLimitExceeded
exception raised.cost¶ – The cost of a hit or a function that takes no parameters and returns the cost as an integer (default:
1
).
- exempt(obj: Blueprint, *, flags: ExemptionScope = ExemptionScope.APPLICATION | ExemptionScope.DEFAULT) Blueprint [source]#
- exempt(obj: Callable[[...], R], *, flags: ExemptionScope = ExemptionScope.APPLICATION | ExemptionScope.DEFAULT) Callable[[...], R]
- exempt(*, flags: ExemptionScope = ExemptionScope.APPLICATION | ExemptionScope.DEFAULT) Callable[[Callable[[P], R]], Callable[[P], R]] | Callable[[Blueprint], Blueprint]
Mark a view function or all views in a blueprint as exempt from rate limits.
- Parameters:
obj¶ – view function or blueprint to mark as exempt.
flags¶ – Controls the scope of the exemption. By default application wide limits and defaults configured on the extension are opted out of. Additional flags can be used to control the behavior when
obj
is a Blueprint that is nested under another Blueprint or has other Blueprints nested under it (See Nested Blueprints)
The method can be used either as a decorator without any arguments (the default flags will apply and the route will be exempt from default and application limits:
@app.route("...") @limiter.exempt def route(...): ...
Specific exemption flags can be provided at decoration time:
@app.route("...") @limiter.exempt(flags=ExemptionScope.APPLICATION) def route(...): ...
If an entire blueprint (i.e. all routes under it) are to be exempted the method can be called with the blueprint as the first parameter and any additional flags:
bp = Blueprint(...) limiter.exempt(bp) limiter.exempt( bp, flags=ExemptionScope.DEFAULT|ExemptionScope.APPLICATION|ExemptionScope.ANCESTORS )
- request_filter(fn: Callable[[], bool]) Callable[[], bool] [source]#
decorator to mark a function as a filter to be executed to check if the request is exempt from rate limiting.
- Parameters:
fn¶ – The function will be called before evaluating any rate limits to decide whether to perform rate limit or skip it.
- check() None [source]#
Explicitly check the limits for the current request. This is only relevant if the extension was initialized with
auto_check
set toFalse
- Raises:
RateLimitExceeded
- property limiter: RateLimiter#
Instance of the rate limiting strategy used for performing rate limiting.
- property current_limit: RequestLimit | None#
Get details for the most relevant rate limit used in this request.
In a scenario where multiple rate limits are active for a single request and none are breached, the rate limit which applies to the smallest time window will be returned.
Important
The value of
remaining
inRequestLimit
is after deduction for the current request.For example:
@limit("1/second") @limit("60/minute") @limit("2/day") def route(...): ...
Request 1 at
t=0
(no breach): this will return the details for for1/second
Request 2 at
t=1
(no breach): it will still return the details for1/second
Request 3 at
t=2
(breach): it will return the details for2/day
- property current_limits: List[RequestLimit]#
Get a list of all rate limits that were applicable and evaluated within the context of this request.
The limits are returned in a sorted order by smallest window size first.
- identify_request() str [source]#
Returns the identity of the request (by default this is the
flask.Request.endpoint
associated by the view function that is handling the request). The behavior can be customized by initializing the extension with a callable argument forrequest_identifier
.
Utilities#
- flag ExemptionScope(value)[source]#
Flags used to configure the scope of exemption when used in conjunction with
exempt()
.Valid values are as follows:
- NONE = <ExemptionScope.NONE: 0>#
- APPLICATION = <ExemptionScope.APPLICATION: 1>#
- DEFAULT = <ExemptionScope.DEFAULT: 2>#
- DESCENDENTS = <ExemptionScope.DESCENDENTS: 4>#
- ANCESTORS = <ExemptionScope.ANCESTORS: 8>#
Exceptions#
- exception RateLimitExceeded(limit: Limit, response: Response | None = None)[source]#
Exception raised when a rate limit is hit.
- Parameters:
limit – The actual rate limit that was hit. Used to construct the default response message
response – Optional pre constructed response. If provided it will be rendered by flask instead of the default error response of
HTTPException