0

I am trying to setup a Flask API limiter for each user. The following code limits an IP Address to 3 request per minute.

from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

limiter = Limiter(
    key_func=get_remote_address, #limit by IP Address
    storage_uri="redis://localhost:6379",
    strategy="moving-window"
)

@api.route('/api/submit-code')
@limiter.limit('3 per minute')
def submit_code():
    user_id = session.get("user_id")

    if not user_id:
        return jsonify({"error": "Unauthorized"}), 401

How can I change this to limit the user instead of IP address? I am using server sessions so I'm not sure how to include user_id in the limiter decorator.

Sam R
  • 31
  • 3
  • 10

1 Answers1

0

I ended up modifying the decorator to the following:

@limiter.limit('3 per minute', key_func = lambda : session.get("user_id"))

The limiter will not apply to users that are not logged in. You can simply add a check in the function for this like the OP.

Sam R
  • 31
  • 3
  • 10