flask-limiter icon indicating copy to clipboard operation
flask-limiter copied to clipboard

How to apply limits to specific paths by checking the passed variable

Open Martini002 opened this issue 2 years ago • 3 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

Martini002 avatar Nov 05 '23 02:11 Martini002

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.

alisaifee avatar Nov 22 '23 18:11 alisaifee

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

Martini002 avatar Nov 22 '23 20:11 Martini002

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

alisaifee avatar Nov 24 '23 21:11 alisaifee

closing due to inactivity

alisaifee avatar Feb 11 '24 18:02 alisaifee