API¶
Extension¶
- class Limiter(key_func: Callable[[], str], *, app: Flask | None = None, default_limits: list[str | Callable[[], str] | Limit] | 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] | ApplicationLimit] | None = None, application_limits_per_method: bool | None = None, application_limits_exempt_when: Callable[[], bool] | None = None, application_limits_deduct_when: Callable[[Response], bool] | 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, swallow_errors: bool | None = None, fail_on_first_breach: bool | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, meta_limits: list[str | Callable[[], str] | MetaLimit] | None = None, on_meta_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
Limiterclass initializes the Flask-Limiter extension.- Parameters:
key_func¶ – a callable that returns the domain to rate limit by.
app¶ –
flask.Flaskinstance to initialize the extension with.default_limits¶ – a list of strings, callables returning strings denoting default limits or
Limitinstances 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.Responseobject 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 list of strings, callables returning strings for limits or
ApplicationLimitthat are applied to the entire application (i.e a shared limit for all routes)application_limits_per_method¶ – whether application limits are applied per method, per route or as a combination of all method per route.
application_limits_exempt_when¶ – a function that should return True/False to decide if the application limits should be skipped
application_limits_deduct_when¶ – a function that receives the current
flask.Responseobject and returns True/False to decide if a deduction should be made from the application rate limit(s)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-RateLimitresponse headers are written.header_name_mapping¶ – Mapping of header names to use if
Limiter.headers_enabledisTrue. 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_URIstorage_options¶ – kwargs to pass to the storage implementation upon instantiation.
swallow_errors¶ – whether to swallow any errors when hitting a rate limit. An exception will still be logged. default
Falsefail_on_first_breach¶ – whether to stop processing remaining limits after the first breach. default
Trueon_breach¶ – a function that will be called when any limit in this extension is breached. If the function returns an instance of
flask.Responsethat will be the response embedded into theRateLimitExceededexception raised.meta_limits¶ – a list of strings, callables returning strings for limits or
MetaLimitthat are used to control the upper limit of a requesting client hitting any configured rate limit. Once a meta limit is exceeded all subsequent requests will raise aRateLimitExceededfor the duration of the meta limit window.on_meta_breach¶ – a function that will be called when a meta limit in this extension is breached. If the function returns an instance of
flask.Responsethat will be the response embedded into theRateLimitExceededexception raised.in_memory_fallback¶ – a 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
Falseretry_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.endpointenabled¶ – 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 | Callable[[], str] | None = None, exempt_when: Callable[[], bool] | None = None, override_defaults: bool = True, deduct_when: Callable[[Response], bool] | None = None, on_breach: None | Callable[[RequestLimit], Response | None] = None, cost: int | Callable[[], int] = 1, scope: str | Callable[[str], str] | None = None, meta_limits: Sequence[str | Callable[[], str] | MetaLimit] | None = None) RouteLimit[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.
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
Blueprintthe 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.Responseobject 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.Responsethat will be the response embedded into theRateLimitExceededexception 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
Added 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.
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
Blueprintthe 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.Responseobject 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.Responsethat will be the response embedded into theRateLimitExceededexception 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 | ExemptionScope.META) Blueprint[source]¶
- exempt(obj: Callable[[...], R], *, flags: ExemptionScope = ExemptionScope.APPLICATION | ExemptionScope.DEFAULT | ExemptionScope.META) Callable[[...], R]
- exempt(*, flags: ExemptionScope = ExemptionScope.APPLICATION | ExemptionScope.DEFAULT | ExemptionScope.META) 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, defaults configured on the extension and meta limits are opted out of. Additional flags can be used to control the behavior when
objis 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.
- 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
remaininginRequestLimitis 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/secondRequest 2 at
t=1(no breach): it will still return the details for1/secondRequest 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.endpointassociated by the view function that is handling the request). The behavior can be customized by initializing the extension with a callable argument forrequest_identifier.
Limit objects¶
The following dataclasses can be used to define rate limits with more
granularity than what is available through the Limiter constructor
if needed (especially for default, application wide and meta limits).
- class Limit(limit_provider: Callable[[], str] | str, key_function: Callable[[], str] | None = None, scope: str | Callable[[str], str] | None = None, cost: Callable[[], int] | int | None = None, shared: bool = False, methods: Sequence[str] | None = None, per_method: bool = False, error_message: str | Callable[[], str] | None = None, meta_limits: Iterable[Callable[[], str] | str | MetaLimit] | None = None, exempt_when: Callable[[], bool] | None = None, deduct_when: Callable[[Response], bool] | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, finalized: bool = True)[source]¶
The definition of a rate limit to be used by the extension as a default limit:
def default_key_function(): return request.remote_addr def username_key_function(): return request.headers.get("username", "guest") limiter = flask_limiter.Limiter( default_key_function, default_limits = [ # 10/second by username flask_limiter.Limit("10/second", key_function=username_key_function), # 100/second by ip (i.e. default_key_function) flask_limiter.Limit("100/second), ] ) limit.init_app(app)
For application wide limits see
ApplicationLimitFor meta limits see
MetaLimit
- limit_provider: Callable[[], str] | str¶
Rate limit string or a callable that returns a string. Rate limit string notation for more details.
- key_function: Callable[[], str] | None = None¶
Callable to extract the unique identifier for the rate limit. If not provided the key_function will default to the key function that the
Limiterwas initialized with (Limiter.key_func)
- scope: str | Callable[[str], str] | None = None¶
A string or callable that returns a unique scope for the rate limit. The scope is combined with current endpoint of the request if
sharedisFalse
- cost: Callable[[], int] | int | None = None¶
The cost of a hit or a function that takes no parameters and returns the cost as an integer (Default:
1).
If this a shared limit (i.e. to be used by different endpoints)
- methods: Sequence[str] | None = None¶
If specified, only the methods in this list will be rate limited.
- error_message: str | Callable[[], str] | None = None¶
String (or callable that returns one) to override the error message used in the response.
- meta_limits: Iterable[Callable[[], str] | str | MetaLimit] | None = None¶
Meta limits to trigger everytime this rate limit definition is exceeded
- exempt_when: Callable[[], bool] | None = None¶
Callable used to decide if the rate limit should skipped.
- deduct_when: Callable[[Response], bool] | None = None¶
A function that receives the current
flask.Responseobject and returns True/False to decide if a deduction should be done from the rate limit
- on_breach: Callable[[RequestLimit], Response | None] | None = None¶
A function that will be called when this limit is breached. If the function returns an instance of
flask.Responsethat will be the response embedded into theRateLimitExceededexception raised.
- class ApplicationLimit(limit_provider: Callable[[], str] | str, key_function: Callable[[], str] | None = None, cost: Callable[[], int] | int | None = None, methods: Sequence[str] | None = None, per_method: bool = False, error_message: str | Callable[[], str] | None = None, meta_limits: Iterable[Callable[[], str] | str | MetaLimit] | None = None, exempt_when: Callable[[], bool] | None = None, deduct_when: Callable[[Response], bool] | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, finalized: bool = True, *, scope: str | Callable[[str], str] | None = 'global')[source]¶
Variant of
Limitto be used for declaring an application wide limit that can be passed toLimiteras one of the members ofLimiter.application_limits- scope: str | Callable[[str], str] | None = 'global'¶
The scope to use for the application wide limit
- cost: Callable[[], int] | int | None = None¶
The cost of a hit or a function that takes no parameters and returns the cost as an integer (Default:
1).
- deduct_when: Callable[[Response], bool] | None = None¶
A function that receives the current
flask.Responseobject and returns True/False to decide if a deduction should be done from the rate limit
- error_message: str | Callable[[], str] | None = None¶
String (or callable that returns one) to override the error message used in the response.
- exempt_when: Callable[[], bool] | None = None¶
Callable used to decide if the rate limit should skipped.
- key_function: Callable[[], str] | None = None¶
Callable to extract the unique identifier for the rate limit. If not provided the key_function will default to the key function that the
Limiterwas initialized with (Limiter.key_func)
- meta_limits: Iterable[Callable[[], str] | str | MetaLimit] | None = None¶
Meta limits to trigger everytime this rate limit definition is exceeded
- methods: Sequence[str] | None = None¶
If specified, only the methods in this list will be rate limited.
- on_breach: Callable[[RequestLimit], Response | None] | None = None¶
A function that will be called when this limit is breached. If the function returns an instance of
flask.Responsethat will be the response embedded into theRateLimitExceededexception raised.
- limit_provider: Callable[[], str] | str¶
Rate limit string or a callable that returns a string. Rate limit string notation for more details.
- class MetaLimit(limit_provider: Callable[[], str] | str, cost: Callable[[], int] | int | None = None, methods: Sequence[str] | None = None, per_method: bool = False, error_message: str | Callable[[], str] | None = None, exempt_when: Callable[[], bool] | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, finalized: bool = True, *, key_function: Callable[[], str] | None = None, scope: str | Callable[[str], str] | None = 'meta')[source]¶
Variant of
Limitto be used for declaring a meta limit that can be passed to eitherLimiteras one of the members ofLimiter.meta_limitsor to another instance ofLimitas a member ofLimit.meta_limits- key_function: Callable[[], str] | None = None¶
Callable to extract the unique identifier for the rate limit. If not provided the key_function will fallback to:
the key function of the parent limit this meta limit is declared for
the key function for the
Limiterinstance this meta limit is eventually used with.
- cost: Callable[[], int] | int | None = None¶
The cost of a hit or a function that takes no parameters and returns the cost as an integer (Default:
1).
- error_message: str | Callable[[], str] | None = None¶
String (or callable that returns one) to override the error message used in the response.
- exempt_when: Callable[[], bool] | None = None¶
Callable used to decide if the rate limit should skipped.
- methods: Sequence[str] | None = None¶
If specified, only the methods in this list will be rate limited.
- on_breach: Callable[[RequestLimit], Response | None] | None = None¶
A function that will be called when this limit is breached. If the function returns an instance of
flask.Responsethat will be the response embedded into theRateLimitExceededexception raised.
- limit_provider: Callable[[], str] | str¶
Rate limit string or a callable that returns a string. Rate limit string notation for more details.
For consistency the RouteLimit dataclass is also available to define limits
for decorating routes or blueprints.
- class RouteLimit(limit_provider: Callable[[], str] | str, key_function: Callable[[], str] | None = None, scope: str | Callable[[str], str] | None = None, cost: Callable[[], int] | int | None = None, shared: bool = False, methods: Sequence[str] | None = None, per_method: bool = False, error_message: str | Callable[[], str] | None = None, meta_limits: Iterable[Callable[[], str] | str | MetaLimit] | None = None, exempt_when: Callable[[], bool] | None = None, deduct_when: Callable[[Response], bool] | None = None, on_breach: Callable[[RequestLimit], Response | None] | None = None, finalized: bool = True, *, override_defaults: bool | None = False, limiter: dataclasses.InitVar[Limiter])[source]¶
A variant of
Limitthat can be used to to decorate a flask route or blueprint directly instead of by usingLimiter.limit()orLimiter.shared_limit().Decorating individual routes:
limiter = flask_limiter.Limiter(.....) limiter.init_app(app) @app.route("/") @flask_limiter.RouteLimit("2/second", limiter=limiter) def view_function(): ...
- override_defaults: bool | None = False¶
Whether the decorated limit overrides the default limits (Default:
True).Note
When used with a
Blueprintthe meaning of the parameter extends to any parents the blueprint instance is registered under. For more details see Nested Blueprints
- cost: Callable[[], int] | int | None = None¶
The cost of a hit or a function that takes no parameters and returns the cost as an integer (Default:
1).
- deduct_when: Callable[[Response], bool] | None = None¶
A function that receives the current
flask.Responseobject and returns True/False to decide if a deduction should be done from the rate limit
- error_message: str | Callable[[], str] | None = None¶
String (or callable that returns one) to override the error message used in the response.
- exempt_when: Callable[[], bool] | None = None¶
Callable used to decide if the rate limit should skipped.
- key_function: Callable[[], str] | None = None¶
Callable to extract the unique identifier for the rate limit. If not provided the key_function will default to the key function that the
Limiterwas initialized with (Limiter.key_func)
- meta_limits: Iterable[Callable[[], str] | str | MetaLimit] | None = None¶
Meta limits to trigger everytime this rate limit definition is exceeded
- methods: Sequence[str] | None = None¶
If specified, only the methods in this list will be rate limited.
- on_breach: Callable[[RequestLimit], Response | None] | None = None¶
A function that will be called when this limit is breached. If the function returns an instance of
flask.Responsethat will be the response embedded into theRateLimitExceededexception raised.
- scope: str | Callable[[str], str] | None = None¶
A string or callable that returns a unique scope for the rate limit. The scope is combined with current endpoint of the request if
sharedisFalse
If this a shared limit (i.e. to be used by different endpoints)
- limit_provider: Callable[[], str] | str¶
Rate limit string or a callable that returns a string. Rate limit string notation for more details.
Utilities¶
- class ExemptionScope(*values)[source]¶
Flags used to configure the scope of exemption when used in conjunction with
exempt().- APPLICATION = 1¶
Exempt from application wide “global” limits
- META = 2¶
Exempts from meta limits
- DEFAULT = 4¶
Exempt from default limits configured on the extension
- DESCENDENTS = 8¶
Exempts any nested blueprints. See Nested Blueprints
- ANCESTORS = 16¶
Exempt from any rate limits inherited from ancestor blueprints. See Nested Blueprints
Exceptions¶
- exception RateLimitExceeded(limit: RuntimeLimit, response: Response | None = None)[source]¶
Exception raised when a rate limit is hit.
- Parameters:
limit – The actual rate limit that was hit. This is 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