How to apply limits to specific paths by checking the passed variable
Martini002 opened this issue · comments
I would like to apply the limit to <specific_door>, not the root, by example:
@app.route('/house/<specific_door>', methods=['GET'])
@limiter.limit("1 per minute")
def index():
return f"get in!"
If I try to reach the:
GET /house/door1
I will get in then it will block me for one minute
but in the same minute I would like to try to reach the:
GET /house/door2
I should be able to get in
Is this even possible?
Thanks
Yes, you can achieve this by using a custom request_identifier
(reference) function that includes the variables in the identifier. By default the identity of the request is derived from request.endpoint
which as you might have noticed only points to the view function name. If instead you returned request.path
from your custom function it could satisfy your use case.
Might you have an example of how this custom function should be passed to the Limiter? And how will it be triggered on request, thank you
Something like this:
from flask import Flask, request
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
app = Flask(__name__)
def idfunc():
return request.path
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["1 per 1 minute"],
storage_uri="memory://",
strategy="fixed-window", # or "moving-window",
request_identifier=idfunc
)
@app.route('/house/<specific_door>', methods=['GET'])
def house(specific_door):
return f"opening door number {specific_door}"
app.run()
closing due to inactivity