Skip to main content

Flask-Limit

Build Documentation image image image image

A lightweight, high-performance rate-limiting extension for Flask applications. Flask-Limit protects your API endpoints from brute-force attacks and abuse by restricting how many requests a client can make within a given time window.


Features

  • Flexible Backends: In-memory store for development; Redis for distributed production deployments.
  • ⚙️ Route-Level & Global Controls: Set global limits or override rules on individual routes.
  • 🔌 Auto-Registering Extensibility: Add custom storage backends (MongoDB, DynamoDB, Postgres) simply by subclassing Limiter.
  • 🛠️ Customizable Responses: Customize rate-limit exceeded responses globally or per endpoint.
  • 🏷️ Standard HTTP Headers: Automatically injects X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset headers.

Installation

Install the base package using pip:

pip install flask-limit

Optional Extras

To use third-party storage backends, install the corresponding extra:

# Redis Backend
pip install flask-limit[redis]

# All Backends
pip install flask-limit[all]

Configuration

Configure default behaviors using standard Flask app.config keys:

Config Key Default Value Description
RATELIMIT_LIMIT 100 Default maximum requests allowed per window.
RATELIMIT_PERIOD 60 Default window duration in seconds.
RATELIMIT_KEY_PREFIX "ratelimit" Prefix prepended to backend tracking keys.
RATELIMIT_REDIS_URL "redis://localhost:6379/0" Redis connection URL when using the redis backend.
RATELIMIT_RESPONSE None Application-level fallback for rate limit exceeded responses.

Quickstart

1. In-Memory Backend (Single Process)

Ideal for local testing and single-worker setups:

from flask import Flask, jsonify
from flask_limit import RateLimiter

app = Flask(__name__)
app.config["RATELIMIT_LIMIT"] = 50
app.config["RATELIMIT_PERIOD"] = 60

# Initialize with default memory backend
limiter = RateLimiter(app, limiter="memory")

# Uses application defaults (50 requests / 60s)
@app.route("/api/users")
@limiter.rate_limit
def get_users():
    return jsonify({"users": []})

# Route-specific override (5 requests / 10s)
@app.route("/api/login", methods=["POST"])
@limiter.rate_limit(limit=5, period=10)
def login():
    return jsonify({"status": "authenticated"})

2. Redis Backend (Production / Multi-Worker)

Required for multi-worker environments (Gunicorn, uWSGI) or distributed servers:

from flask import Flask, jsonify
from flask_limit import RateLimiter

app = Flask(__name__)
app.config["RATELIMIT_REDIS_URL"] = "redis://localhost:6379/0"

# Initialize with Redis backend
limiter = RateLimiter(app, limiter="redis")

@app.route("/api/data")
@limiter.rate_limit(limit=100, period=60)
def get_data():
    return jsonify({"data": "ok"})

Customizing Exceeded Limit Responses

When a client hits a rate limit, Flask-Limit returns a 429 Too Many Requests status code. You can customize the response at the application or route level.

Application-Wide Response

Assign a function or response tuple to RATELIMIT_RESPONSE in app.config:

from flask import jsonify
from flask_limit.types import RateLimitInfo

def custom_limit_exceeded(info: RateLimitInfo):
    return jsonify({
        "error": "rate_limit_exceeded",
        "retry_after_seconds": info.reset,
        "max_allowed": info.limit
    }), 429

app.config["RATELIMIT_RESPONSE"] = custom_limit_exceeded

Route-Level Response Override

Pass a callable or tuple directly to the @limiter.rate_limit decorator:

@app.route("/api/strict")
@limiter.rate_limit(
    limit=2,
    period=60,
    response=("Custom 429: Too many requests on this endpoint.", 429)
)
def strict_route():
    return jsonify({"status": "ok"})

Custom Backends

Creating a custom storage backend is seamless. Simply inherit from Limiter and define a name in the class header—Flask-Limit will register it automatically!

from flask_limit.limiters import Limiter

class MemcachedRateLimit(Limiter, name="memcached"):

    @classmethod
    def from_app(cls, app):
        # Build your backend instance using app config
        return cls(server=app.config["MEMCACHED_SERVER"])

    def is_allowed(self, key: str, limit: int, period: int):
        # Return tuple: (allowed: bool, remaining: int, reset: int)
        return True, limit - 1, period

    def cleanup(self, key=None):
        pass

# Use your new custom backend immediately!
limiter = RateLimiter(app, limiter="memcached")

Documentation

For full API references, architecture guides, and Sphinx docs, check out the Documentation in the repository.


License

This project is licensed under the MIT License.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flask_limit-3.0.0.tar.gz (710.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flask_limit-3.0.0-py3-none-any.whl (10.2 kB view details)

Uploaded Python 3

File details

Details for the file flask_limit-3.0.0.tar.gz.

File metadata

  • Download URL: flask_limit-3.0.0.tar.gz
  • Upload date:
  • Size: 710.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for flask_limit-3.0.0.tar.gz
Algorithm Hash digest
SHA256 48301d6431a8eaab5e1945ce8837a7a4d69504c86d8446296ad91efc868143ed
MD5 282b201ab74d718619068d997cc5d8c0
BLAKE2b-256 c5892e892b5f973428eb52de89c2d59b13bd5d68c5ea6384065703c216748a0a

See more details on using hashes here.

Provenance

The following attestation bundles were made for flask_limit-3.0.0.tar.gz:

Publisher: release.yml on tabotkevin/flask_limit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file flask_limit-3.0.0-py3-none-any.whl.

File metadata

  • Download URL: flask_limit-3.0.0-py3-none-any.whl
  • Upload date:
  • Size: 10.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for flask_limit-3.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8cfbc57470666df28cf8a8e6135ee5fa48fd50c350e19fb308db9c45ad1624e1
MD5 34c3487d97c0c7f17dcddf09282c6483
BLAKE2b-256 cdba13a03a8eca229788143454273ad9a7bb57250e470a0c3b8b7455727b50c8

See more details on using hashes here.

Provenance

The following attestation bundles were made for flask_limit-3.0.0-py3-none-any.whl:

Publisher: release.yml on tabotkevin/flask_limit

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

This release

3.0.0 This release

2 files

2.0.5

1 file

2.0.4

1 file

2.0.3

1 file

2.0.2

1 file

2.0.1

1 file

2.0

1 file

1.0.5

1 file

1.0.4

1 file

1.0.3

2 files

1.0.2

2 files

1.0.1

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page