It is very important to control the rate of incoming requests to prevent abuse such as DDoS attacks and maintain the server’s performance and availability. In this article, we will see how to limit the number of incoming requests in the flask application.

Install flask-limiter

Flask does not have built-in support for request limiting but this can be done easily using the extension like Flask-Limiter.

Use pip to install the flask limiter

pip install Flask-Limiter

Setup

After installing the application, you can integrate it into your flask application as shown below.

from flask import Flask
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

app = Flask(__name__)
limiter = Limiter(
    app,
    key_func=get_remote_address,
    default_limits=["200 per day", "50 per hour"]
)

In the above setup, get_remote_address is used to identify unique clients based on their IP addresses, by default we limit 200 requests per day and 50 requests per hour.

Similarly, we can also apply limits to routes.

from flask import Flask, jsonify
from flask_limiter import Limiter

app = Flask(__name__)
limiter = Limiter(app, key_func=lambda: "global")

@app.route('/api/resource')
@limiter.limit("5 per minute")
def limited_resource():
    return jsonify(message="Access granted!")

if __name__ == '__main__':
    app.run(debug=True)

In the above example, we limit the /api/resource endpoint to 5 requests per minute. You can customize the limit based on your needs.

You can also customize the rate limits for different endpoints by specifying them in the @limiter.limit decorator.

Categorized in:

Tagged in: