Registry / web-framework / django-ratelimit

django-ratelimit

JSON →
library4.1.0pypypi✓ verified 25d ago

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.

pip install django-ratelimit
INSTALL
IMPORT
SIG · DJANGO-RATELIMIT
D
django-ratelimit
web-frameworkpythonv4.1.0
Install
1.5s avg
Import
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.000s · 17.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.5s · import 0.000s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ALL
from django_ratelimit import ALL
from django_ratelimit.decorators import ratelimit
UNSAFE
from django_ratelimit import UNSAFE
VERSION
from django_ratelimit import VERSION

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__})")
Debug
Known issues
breakingThe package name was changed from `ratelimit` to `django_ratelimit` in version 4.0.0. All import statements must be updated accordingly (e.g., `from django_ratelimit.decorators import ratelimit`).
fix
Update all `import` statements from `ratelimit` to `django_ratelimit`.
affects: >=4.0.0
breakingThe default behavior of the `@ratelimit` decorator's `block` argument changed from `False` to `True` in version 4.0.0. Views will now block requests by default if the rate limit is exceeded, instead of just annotating the request.
fix
To retain the old behavior of only annotating the request, explicitly set `block=False` on the decorator: `@ratelimit(key='ip', rate='5/m', block=False)`.
affects: >=4.0.0
breakingVersion 4.0.0 dropped support for Python versions older than 3.7 and Django versions older than 3.2.
fix
Ensure your project uses Python 3.7+ and Django 3.2+ when upgrading to `django-ratelimit` 4.0.0 or newer.
affects: >=4.0.0
gotcha`django-ratelimit` requires a Django cache backend that supports atomic increment operations (e.g., Memcached or Redis). The database cache backend does *not* support this and will lead to incorrect rate limiting behavior.
fix
Configure your Django `CACHES` setting to use a backend like `django.core.cache.backends.memcached.PyMemcacheCache` or `django_redis.cache.RedisCache`.
affects: All versions
deprecatedSince version 3.0, the `@ratelimit` decorator no longer directly supports class methods, and `RatelimitMixin` was dropped. Instead, use `@method_decorator` for class-based views.
fix
For class-based views, wrap `@ratelimit` with `@method_decorator`. Example: `from django.utils.decorators import method_decorator; @method_decorator(ratelimit(key='ip', rate='5/m'), name='dispatch') class MyView(View): ...`
affects: >=3.0.0
Upgrade
Version history
4.1.0latest on PyPI · released Jul 24, 2023
Audit
Dependencies
DjangorequiredCore framework dependency for the library's functionality.
Agent activity
18 hits · last 30 days
node
16
OpenAI (training)
1
Resources