Flask-Limiter

4.1.1 · active · verified Sun Mar 29

Flask-Limiter is an active Python extension that adds rate limiting capabilities to Flask applications, preventing abuse and ensuring stability. It allows configuration of limits at various levels (application-wide, per Blueprint, per route) and supports multiple storage backends like Redis, Memcached, MongoDB, and Valkey. The current version is 4.1.1, with a regular release cadence.

Warnings

Install

Imports

Quickstart

Initializes a Flask application with global and per-route rate limits. It uses `get_remote_address` as the default key function and specifies a default storage URI. Routes demonstrate application-wide limits, specific route limits, combined limits, and exemptions. An error handler for HTTP 429 is included for custom responses.

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

app = Flask(__name__)

# Configure storage_uri, using in-memory for example, or from an environment variable
# In-memory storage is for development/testing only and should not be used in production with multiple workers.
# For production, use backends like Redis: 'redis://localhost:6379'
storage_uri = os.environ.get('FLASK_RATELIMIT_STORAGE_URI', 'memory://')

limiter = Limiter(
    key_func=get_remote_address,
    app=app,
    default_limits=["200 per day", "50 per hour"],
    storage_uri=storage_uri,
    strategy="fixed-window" # Or 'moving-window', 'sliding-window-counter'
)

@app.route("/slow")
@limiter.limit("1 per day")
def slow():
    return ":("

@app.route("/medium")
@limiter.limit("1/second", override_defaults=False)
def medium():
    return ":|"

@app.route("/fast")
def fast():
    return ":)"

@app.route("/ping")
@limiter.exempt
def ping():
    return "PONG"

# Example error handler for rate limit exceeded (HTTP 429)
@app.errorhandler(429)
def ratelimit_handler(e):
    return f"Rate limit exceeded: {e.description}", 429

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

view raw JSON →