skip to Main Content

Can i set limit on http request header in flask?

My request header is store in redis and One is added for each request in redis.
for example:

one : 3

tow : 5

one , tow and … is my request header by key= CLIENT-KEY.


    app = Flask(__name__)
    limiter = Limiter(
        app,
        key_func=get_remote_address,
        default_limits=["200 per day", "50 per hour"]
    )
    
    redis_cache = redis.Redis(host='127.0.0.1', port=6379, db=0,
                              password='redis', charset="utf-8", decode_responses=True)
    
    number = 0
    
    
    @app.route('/', methods=['POST'])
    @limiter.limit("1 per minute", key_func=get_remote_address)
    def api_message():
        try:
            target = request.headers['CLIENT-KEY']
            global number
            if redis_cache.__contains__(target):
                a = int(redis_cache.get(target))
                redis_cache.set(target, a + 1)
    
                return redis_cache.get(target)
    
            else:
                number = 0
                number += 1
                redis_cache.set(target, number)
                return redis_cache.get(target)
    
        except:
            my_key_list = redis_cache.keys()
            return redis_cache.get(target)

NOW HOW CAN I LIMIT REQUEST HEADER?

for example:
each CLIENT-KEY can request only 10 per minute

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem


    from flask import Flask, request, make_response
    from flask import jsonify
    from flask_limiter import Limiter
    
    
    
    def get_client_key():
        return request.headers.get('CLIENT-KEY')
    
    
    app = Flask(__name__)
    limiter = Limiter(app, key_func=get_client_key)
    
    
    
    
    
    @app.errorhandler(429)
    def ratelimit_handler(e):
        return make_response(
            jsonify(
                {"message": f"Too many request from {request.headers.get('CLIENT-KEY')}"}), 429
        )
    
    
    @app.route('/', methods=['POST'])
    @limiter.limit('10/minute')
    

    This link might be helpful you. this is my github repo.


  2. It seems you need some dynamic limit. You can access your request headers like below:

    from flask import request
    request.headers.get('your-header-name')
    

    This link might be helpful for how to define some dynamic limit.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search