Django Ratelimit

4.1.0 · active · verified Thu Apr 09

Django Ratelimit is a cache-based rate-limiting library for Django applications, currently at version 4.1.0. It provides decorators and middleware to limit the rate of client requests, helping to prevent abuse and manage server resources. The library typically has an active release cadence, with major versions aligning with Django's own release cycle and minor versions for fixes and features.

Warnings

Install

Imports

Quickstart

To use `django-ratelimit`, first ensure you have a Django cache backend configured that supports atomic increment operations (like Memcached or Redis, not the default database cache). Then, apply the `@ratelimit` decorator to your Django views. The `key` parameter determines how requests are grouped (e.g., by 'ip' or 'user'), `rate` defines the limit (e.g., '5/m' for 5 per minute), and `block=True` will return a 429 Too Many Requests response if the limit is exceeded.

from django.http import HttpResponse
from django.conf import settings
from django.core.cache import cache
from django_ratelimit.decorators import ratelimit

# Ensure Django settings are configured for a cache backend supporting atomic increments
# (e.g., Memcached or Redis).
# In a real project, this would be in settings.py
if not settings.configured:
    settings.configure(
        DEBUG=True,
        SECRET_KEY='a-very-secret-key',
        CACHES={
            'default': {
                'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
                'LOCATION': 'unique-snowflake',
            }
        },
        ROOT_URLCONF=__name__,
        INSTALLED_APPS=[
            'django_ratelimit'
        ]
    )

# Clear cache for repeatable testing
cache.clear()

@ratelimit(key='ip', rate='5/m', block=True)
def my_rate_limited_view(request):
    """This view allows 5 requests per minute per IP address."""
    return HttpResponse("Hello from a rate-limited view!")

# Example of how you might test it (not part of typical quickstart)
if __name__ == '__main__':
    from django.urls import path
    from django.test import RequestFactory

    urlpatterns = [
        path('limited/', my_rate_limited_view),
    ]

    factory = RequestFactory()
    for i in range(7):
        request = factory.get('/limited/')
        request.META['REMOTE_ADDR'] = '127.0.0.1' # Simulate client IP
        try:
            response = my_rate_limited_view(request)
            print(f"Request {i+1}: Status {response.status_code}")
        except Exception as e:
            print(f"Request {i+1}: Blocked (Exception: {type(e).__name__})")

view raw JSON →