### Install Django for development Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/contributing.rst Instructions for setting up the development environment by installing Django using pip within a virtual environment. ```sh $ pip install Django ``` -------------------------------- ### Install Django Ratelimit via pip Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/index.rst This snippet provides the command to install the `django-ratelimit` package using pip, the standard Python package installer. Ensure you have pip configured correctly in your environment. ```shell pip install django-ratelimit ``` -------------------------------- ### Diverse Ratelimit Decorator Usage Examples Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst A collection of practical examples demonstrating various configurations and advanced uses of the `ratelimit` decorator, including conditional limiting, custom keys, and grouping. ```Python @ratelimit(key='ip', rate='5/m', block=False) def myview(request): # Will be true if the same IP makes more than 5 POST # requests/minute. was_limited = getattr(request, 'limited', False) return HttpResponse() @ratelimit(key='ip', rate='5/m', block=True) def myview(request): # If the same IP makes >5 reqs/min, will raise Ratelimited return HttpResponse() ``` ```Python @ratelimit(key='post:username', rate='5/m', method=['GET', 'POST'], block=False) def login(request): # If the same username is used >5 times/min, this will be True. # The `username` value will come from GET or POST, determined by the # request method. was_limited = getattr(request, 'limited', False) return HttpResponse() ``` ```Python @ratelimit(key='post:username', rate='5/m') @ratelimit(key='post:tenant', rate='5/m') def login(request): # Use multiple keys by stacking decorators. return HttpResponse() ``` ```Python @ratelimit(key='get:q', rate='5/m') @ratelimit(key='post:q', rate='5/m') def search(request): # These two decorators combine to form one rate limit: the same search # query can only be tried 5 times a minute, regardless of the request # method (GET or POST) return HttpResponse() ``` ```Python @ratelimit(key='ip', rate='4/h') def slow(request): # Allow 4 reqs/hour. return HttpResponse() ``` ```Python get_rate = lambda g, r: None if r.user.is_authenticated else '100/h' @ratelimit(key='ip', rate=get_rate) def skipif1(request): # Only rate limit anonymous requests return HttpResponse() ``` ```Python @ratelimit(key='user_or_ip', rate='10/s') @ratelimit(key='user_or_ip', rate='100/m') def burst_limit(request): # Implement a separate burst limit. return HttpResponse() ``` ```Python @ratelimit(group='expensive', key='user_or_ip', rate='10/h') def expensive_view_a(request): return something_expensive() @ratelimit(group='expensive', key='user_or_ip', rate='10/h') def expensive_view_b(request): # Shares a counter with expensive_view_a return something_else_expensive() ``` ```Python @ratelimit(key='header:x-cluster-client-ip') def post(request): # Uses the X-Cluster-Client-IP header value. return HttpResponse() ``` ```Python @ratelimit(key=lambda g, r: r.META.get('HTTP_X_CLUSTER_CLIENT_IP', r.META['REMOTE_ADDR'])) def myview(request): # Use `X-Cluster-Client-IP` but fall back to REMOTE_ADDR. return HttpResponse() ``` -------------------------------- ### Install tox for multi-version testing Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/contributing.rst Command to install the tox testing automation tool, which enables running tests against multiple Python and Django versions. ```sh $ pip install tox ``` -------------------------------- ### Using Special HTTP Method Shortcuts with Ratelimit Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst This example demonstrates the use of `ratelimit.ALL` and `ratelimit.UNSAFE` shortcuts for specifying HTTP methods to rate-limit. `ALL` applies to all methods, while `UNSAFE` covers `POST`, `PUT`, `PATCH`, `DELETE`. ```Python from django_ratelimit.decorators import ratelimit @ratelimit(key='ip', method=ratelimit.ALL) @ratelimit(key='ip', method=ratelimit.UNSAFE) def myview(request): pass ``` -------------------------------- ### Apply Ratelimit Decorator to Django Views Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/installation.rst This example illustrates how to enforce ratelimits on Django views using the `@ratelimit` decorator from `django_ratelimit.decorators`. It showcases two common use cases: applying the decorator to a function-based view (`myview`) to limit requests to 10 per minute per user or IP, and applying it to a method within a class-based view (`MyView.get`) to limit requests to 1 per second. The `key` parameter specifies the basis for rate limiting (e.g., 'user_or_ip'), and `rate` defines the maximum allowed requests within a given time frame. ```python from django_ratelimit.decorators import ratelimit @ratelimit(key='user_or_ip', rate='10/m') def myview(request): # limited to 10 req/minute for a given user or client IP # or on class methods class MyView(View): @method_decorator(ratelimit(key='user_or_ip', rate='1/s')) def get(self, request): # limited to 1 req/second ``` -------------------------------- ### Configure Django Ratelimit Cache Backend Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/installation.rst This snippet demonstrates how to specify a dedicated cache backend for `django-ratelimit` within your Django project's `settings.py`. It defines a new cache entry named 'cache-for-ratelimiting' and then instructs `django-ratelimit` to use this specific cache via the `RATELIMIT_USE_CACHE` setting. This configuration is essential when the default cache is not suitable or a separate cache is desired for ratelimiting operations. ```python # your_apps_settings.py CACHES = { 'default': {}, 'cache-for-ratelimiting': {}, } RATELIMIT_USE_CACHE = 'cache-for-ratelimiting' ``` -------------------------------- ### Django Ratelimit: Applying Different Limits for GET and POST Methods (Post-0.5) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Illustrates how to apply distinct rate limits based on HTTP methods (e.g., GET and POST) to a single view using multiple @ratelimit decorators in django-ratelimit 0.5+. This allows for fine-grained control over request rates. ```Python @ratelimit(key='ip', method='GET', rate='1000/h') @ratelimit(key='ip', method='POST', rate='100/h') def maybe_expensive(request): pass ``` -------------------------------- ### Ratelimit Decorator Callable Key Example (Python) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/keys.rst Illustrates how to define a custom callable function to generate a ratelimit key. This function receives the `group` and `request` objects as arguments and must return a bytestring or unicode object to be used as the key. This allows for highly customized ratelimiting logic. ```Python def my_key(group, request): return request.META['REMOTE_ADDR'] + request.user.username ``` -------------------------------- ### Django Ratelimit: Combining General and Specific Method Rate Limits (Post-0.5) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Demonstrates applying a general rate limit for multiple HTTP methods (GET, POST) and a more specific, stricter limit for a single method (POST) on the same view in django-ratelimit 0.5+. This shows how limits can interact when methods overlap. ```Python @ratelimit(key='ip', method=['GET', 'POST'], rate='1000/h') @ratelimit(key='ip', method='POST', rate='100/h') def maybe_expensive(request): pass ``` -------------------------------- ### Apply ratelimit decorator with custom rate to Django view Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/index.rst This Python example shows how to use the `@ratelimit` decorator with a specified rate, such as '100/h' for 100 requests per hour. This allows for fine-grained control over the request limits for different view functions. ```python @ratelimit(key='ip', rate='100/h') def secondview(request): # ... ``` -------------------------------- ### Apply Ratelimit Decorator to Django Class-Based View Method Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Demonstrates how to apply the `@method_decorator(ratelimit(...))` to a specific method within a Django class-based view to limit requests based on IP and GET method. ```python @method_decorator(ratelimit(key='ip', rate='1/m', method='GET')) def get(self, request): pass ``` -------------------------------- ### Define a Custom Django View for 429 Too Many Requests Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/cookbook/429.rst This Python code defines two examples of a custom Django view function, `ratelimited_error`, designed to handle rate-limiting exceptions. The first example renders an HTML template with an HTTP 429 status, while the second returns a JSON response, demonstrating flexibility for different application types (e.g., HTML-based vs. JSON APIs). ```python # myapp/views.py def ratelimited_error(request, exception): # e.g. to return HTML return render(request, 'ratelimited.html', status=429) def ratelimited_error(request, exception): # or other types: return JsonResponse({'error': 'ratelimited'}, status=429) ``` -------------------------------- ### Django Ratelimit Decorator by IP and Username Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/security.rst This example shows how to apply multiple `@ratelimit` decorators to a view, combining IP-based limiting with username-based limiting. This dual approach significantly enhances protection against brute-force and dictionary attacks by considering both the source IP and the target username, making it more robust than single-key limiting and harder for attackers to circumvent. ```Python @ratelimit(key='ip') @ratelimit(key='post:username') def login_view(request): pass ``` -------------------------------- ### Django Ratelimit Decorator (Post-0.5 Stacked Single-Key) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst This example illustrates the updated usage of the `@ratelimit` decorator from `django-ratelimit` version 0.5 onwards. Each decorator now handles a single, specific key. To achieve complex rate-limiting scenarios that previously used multiple keys, multiple `@ratelimit` decorators are stacked, allowing for more granular control and new patterns like distinct GET/POST limits. ```Python @ratelimit(key='ip') @ratelimit(key='post:username') @ratelimit(key='get:username') @ratelimit(key=mykeysfunc) def someview(request): # ... ``` -------------------------------- ### Handle Django Ratelimited Exception in Custom 403 Handler Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Provides an example of a custom `handler403` function in Django that specifically checks for and handles the `Ratelimited` exception, returning a 429 (Too Many Requests) status code for rate-limited responses. ```python def handler403(request, exception=None): if isinstance(exception, Ratelimited): return HttpResponse('Sorry you are blocked', status=429) return HttpResponseForbidden('Forbidden') ``` -------------------------------- ### Django Ratelimit Decorator Using Custom Header Key Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/security.rst This example demonstrates how to use the `@ratelimit` decorator with a custom header as the key. This is particularly useful when a trusted header, such as `X-Real-IP`, reliably contains only the client's IP address, unlike `X-Forwarded-For` which can contain multiple IPs. This allows for precise rate limiting based on a specific, trusted header value. ```Python @ratelimit(key='header:x-real-ip', rate='10/s') ``` -------------------------------- ### Implement Per-User Ratelimits with a Django Model Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/cookbook/per-user.rst This snippet defines a `Ratelimit` Django model to store group-specific and user-specific rate limits. It includes a `get` class method to retrieve rates, falling back to a default if a user-specific rate isn't found. It also shows a `per_user` function that retrieves the appropriate rate based on the authenticated user and demonstrates how to apply this custom rate function to a Django view using the `@ratelimit` decorator. ```python # myapp/models.py class Ratelimit(models.Model): group = models.CharField(db_index=True) user = models.ForeignKey(null=True) # One option for "default" rate = models.CharField() @classmethod def get(cls, group, user=None): # use cache if possible try: return cls.objects.get(group=group, user=user) except cls.DoesNotExist: return cls.objects.get(group=group, user=None) # myapp/ratelimits.py from myapp.models import Ratelimit def per_user(group, request): if request.user.is_authenticated: return Ratelimit.get(group, request.user) return Ratelimit.get(group) # myapp/views.py @login_required @ratelimit(group='search', key='user', rate='myapp.ratelimits.per_user') def search_view(request): # ... ``` -------------------------------- ### Migrate `@ratelimit` Decorator on Class Methods with `@method_decorator` (2.0 to 3.0) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst In version 3.0, the `@ratelimit` decorator no longer works directly on class methods. It must now be wrapped with Django's `@method_decorator` utility. This example demonstrates the migration from direct application to using `@method_decorator` for class methods. ```python from django.views.generic import View from ratelimit.decorators import ratelimit class MyView(View): @ratelimit(key='ip', rate='1/m', method='GET') def get(self, request): pass ``` ```python from django.utils.decorators import method_decorator from django.views.generic import View from ratelimit.decorators import ratelimit class MyView(View): @method_decorator(ratelimit(key='ip', rate='1/m', method='GET')) def get(self, request): pass ``` -------------------------------- ### Execute Django project tests Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/contributing.rst Command to run the project's test suite directly using the provided run script. ```sh $ ./run.sh test ``` -------------------------------- ### Django Ratelimit Decorator API Reference Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Detailed API documentation for the `ratelimit` decorator, outlining its arguments, their types, default values, and descriptions. It covers parameters like `group`, `key`, `rate`, `method`, and `block`. ```APIDOC ratelimit(group=None, key=, rate=None, method=ALL, block=True) group: None. A group of rate limits to count together. Defaults to the dotted name of the view. key: What key to use, see Keys. rate: '5/m'. The number of requests per unit time allowed. Valid units are: s (seconds), m (minutes), h (hours), d (days). Also accepts callables. A rate of 0/s disallows all requests. A rate of None means "no limit" and will allow all requests. method: ALL. Which HTTP method(s) to rate-limit. May be a string, a list/tuple of strings, or the special values for ALL or UNSAFE. block: True. Whether to block the request instead of annotating. ``` -------------------------------- ### Importing Django Ratelimit Decorator Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst This snippet shows the standard way to import the `ratelimit` decorator from the `django_ratelimit.decorators` module. ```Python from django_ratelimit.decorators import ratelimit ``` -------------------------------- ### Run tests across Django versions with tox Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/contributing.rst Command to execute the project's test suite using tox, facilitating testing against various Django and Python environments. ```sh $ tox ``` -------------------------------- ### Import Core Django Ratelimit Functions Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Imports the `get_usage` and `is_ratelimited` functions from `django_ratelimit.core` for direct programmatic access to rate limiting functionality, useful for conditional rate limit application. ```python from django_ratelimit.core import get_usage, is_ratelimited ``` -------------------------------- ### Ratelimit Decorator Common String Keys Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/keys.rst Describes the predefined string values that can be used for the `key=` argument in the Django ratelimit decorator. These provide shortcuts for commonly used ratelimit keys based on request attributes like IP address, GET/POST data, headers, or user information. ```APIDOC Key Type: 'ip' Description: Use the request IP address (i.e. request.META['REMOTE_ADDR']). Note: If you are using a reverse proxy, make sure this value is correct or use an appropriate 'header:' value. Key Type: 'get:X' Description: Use the value of request.GET.get('X', ''). Key Type: 'post:X' Description: Use the value of request.POST.get('X', ''). Key Type: 'header:x-x' Description: Use the value of request.META.get('HTTP_X_X', ''). Note: The value right of the colon will be translated to all-caps and any dashes will be replaced with underscores, e.g.: x-client-ip => X_CLIENT_IP. Key Type: 'user' Description: Use an appropriate value from request.user. Do not use with unauthenticated users. Key Type: 'user_or_ip' Description: Use an appropriate value from request.user if the user is authenticated, otherwise use request.META['REMOTE_ADDR']. Important Note: Missing headers, GET, and POST values will all be treated as empty strings, and ratelimited in the same bucket. Warning: Using user-supplied data directly can allow users to trivially opt out of ratelimiting. ``` -------------------------------- ### Wrap Django View with Ratelimit in URL Patterns Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Illustrates how to apply a ratelimit directly within Django's `urlpatterns` by wrapping a view's `as_view()` method with the `ratelimit` function. This allows for rate limiting configuration directly in URL routing. ```python from django.urls import path from myapp.views import MyView from django_ratelimit.decorators import ratelimit urlpatterns = [ path('/', ratelimit(key='ip', method='GET', rate='1/m')(MyView.as_view())), ] ``` -------------------------------- ### Django Ratelimit Configuration Settings API Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/settings.rst Defines the available settings for configuring the `django-ratelimit` library, including their purpose, default values, and usage details. ```APIDOC RATELIMIT_CACHE_PREFIX: Type: string Default: 'rl:' Description: An optional cache prefix for ratelimit keys (in addition to the PREFIX value defined on the cache backend). RATELIMIT_HASH_ALGORITHM: Type: string (dotted path to callable) Default: 'hashlib.sha256' Description: An optional function to override the default hashing algorithm used to derive the cache key. RATELIMIT_ENABLE: Type: boolean Default: True Description: Set to False to disable rate-limiting across the board. Useful during tests with Django's override_settings. RATELIMIT_USE_CACHE: Type: string Default: 'default' Description: The name of the cache (from the CACHES dict) to use. Requires a Django cache backend that supports atomic increment operations (e.g., Memcached, Redis). RATELIMIT_VIEW: Type: string (dotted path to view) Default: None (required if using RatelimitMiddleware) Description: The string import path to a view to use when a request is ratelimited, in conjunction with RatelimitMiddleware. RATELIMIT_FAIL_OPEN: Type: boolean Default: False Description: Whether to allow requests when the cache backend fails. RATELIMIT_IP_META_KEY: Type: string, callable, or None Default: None Description: Sets the source of the client IP address in the request.META object. Possible Values: - None: Uses request.META['REMOTE_ADDR'] as the source. - Callable object: A callable passed the full request object, must return the client IP address (e.g., lambda r: r.META['HTTP_X_CLIENT_IP']). - Dotted path to a callable: Any string containing a '.' will be treated as a dotted path to a callable, imported and called on the request object. - Any other string: Treated as a key for the request.META object (e.g., 'HTTP_X_REAL_IP'). RATELIMIT_IPV4_MASK: Type: integer Default: 32 Description: IPv4 mask for IP-based rate limit (32 means no masking). RATELIMIT_IPV6_MASK: Type: integer Default: 64 Description: IPv6 mask for IP-based rate limit (64 masks the last 64 bits). RATELIMIT_EXCEPTION_CLASS: Type: string (dotted path to class) Default: None Description: A custom exception class, or a dotted path to a custom exception class, that will be raised by ratelimit when a limit is exceeded and block=True. ``` -------------------------------- ### Django Ratelimit: Stacking Decorators for Burst and Hourly Limits (Post-0.5) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Demonstrates how to apply multiple @ratelimit decorators to a single view in django-ratelimit 0.5+, allowing for different rate limits (e.g., per-minute burst and per-hour overall) on the same key. Note that views with identical decorators do not share limits by default. ```Python @ratelimit(key='ip', rate='100/m') @ratelimit(key='ip', rate='1000/h') def myview(request): pass ``` -------------------------------- ### Django Ratelimit: Pre-0.5 Rate Limit Sharing Behavior Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Illustrates the confusing rate limit sharing behavior in django-ratelimit versions prior to 0.5, where limits were implicitly shared based on keys like IP or fields, leading to unintuitive outcomes. ```Python @ratelimit(ip=True, field='username') def both(request): pass @ratelimit(ip=False, field='username') def field_only(request): pass @ratelimit(ip=True) def ip_only(request): pass ``` -------------------------------- ### Apply basic IP-based ratelimit decorator to Django view Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/index.rst This Python code demonstrates how to import and apply the `@ratelimit` decorator to a Django view function. By default, `key='ip'` limits requests based on the client's IP address, preventing abuse from a single source. ```python from django_ratelimit.decorators import ratelimit @ratelimit(key='ip') def myview(request): # ... ``` -------------------------------- ### Applying Ratelimit to Django Class-Based Views Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst This snippet demonstrates how to apply the `ratelimit` decorator to Django class-based views using the `method_decorator` utility from `django.utils.decorators`. ```Python from django.utils.decorators import method_decorator from django.views.generic import View class MyView(View): ``` -------------------------------- ### Django Middleware for Correct Client IP Resolution Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/security.rst This snippet provides a template for a Django middleware function designed to correctly set the `REMOTE_ADDR` in `request.META` when Django is deployed behind a reverse proxy. It's crucial for accurate IP-based rate limiting. The placeholder `[...]` must be replaced with environment-specific logic to extract the true client IP. The middleware should be placed high in the `MIDDLEWARE` settings to ensure it processes the request early. ```Python def reverse_proxy(get_response): def process_request(request): request.META['REMOTE_ADDR'] = # [...] return get_response(request) return process_request ``` ```Python MIDDLEWARE = ( 'path.to.reverse_proxy', # ... ) ``` ```Python @ratelimit(key='ip', rate='10/s') ``` -------------------------------- ### APIDOC: `get_usage` Function Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Retrieves detailed rate limit usage information for a given HTTP request. This function allows for flexible and conditional application of rate limits by providing current count, limit, and time left. ```APIDOC get_usage(request, group=None, fn=None, key=None, rate=None, method=ALL, increment=False) request: The HTTPRequest object. group: A group of rate limits to count together. Defaults to the dotted name of the view. fn: A view function which can be used to calculate the group as if it was decorated by @ratelimit. key: What key to use, see Keys chapter. rate: '5/m' The number of requests per unit time allowed. Valid units are: s (seconds), m (minutes), h (hours), d (days). Also accepts callables. method: ALL Which HTTP method(s) to rate-limit. May be a string, a list/tuple, or None for all methods. increment: False Whether to increment the count or just check. returns: dict or None: Either returns None, indicating that ratelimiting was not active for this request (for some reason) or returns a dict including the current count, limit, time left in the window, and whether this request should be limited. ``` -------------------------------- ### Django Ratelimit Decorator (Pre-0.5 Multi-Key) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst This code snippet demonstrates the usage of the `@ratelimit` decorator in `django-ratelimit` prior to version 0.5. In this older approach, a single decorator instance could specify multiple rate-limiting keys (e.g., IP, field, or a custom function) simultaneously. ```Python @ratelimit(ip=True, field='username', keys=mykeysfunc) def someview(request): # ... ``` -------------------------------- ### Temporarily Disable Django Ratelimit with override_settings Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/settings.rst Demonstrates how to use Django's `override_settings` context manager to temporarily disable rate-limiting during tests or specific operations by setting `RATELIMIT_ENABLE` to `False`. ```python from django.test import override_settings with override_settings(RATELIMIT_ENABLE=False): result = call_the_view() ``` -------------------------------- ### Handle Ratelimited Exception within Django's 403 Handler Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/cookbook/429.rst This Python code demonstrates an alternative approach to handling `Ratelimited` exceptions by modifying an existing `handler403` view. It checks if the exception is an instance of `Ratelimited` and, if so, renders a 429 HTML page; otherwise, it defaults to the standard 403 handling. This method provides granular control over error responses without requiring a separate custom view for 429 errors. ```python from django_ratelimit.exceptions import Ratelimited def my_403_handler(request, exception): if isinstance(exception, Ratelimited): return render(request, '429.html', status=429) return render(request, '403.html', status=403) ``` -------------------------------- ### Define Dynamic Rate Limit with Python Callable Returning String Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/rates.rst This Python function demonstrates how to implement a dynamic rate limit. It checks if the user associated with the request is authenticated. Authenticated users are granted a higher rate limit (1000 requests per minute), while unauthenticated users receive a standard rate limit (100 requests per minute). The function returns the rate as a string. ```python def my_rate(group, request): if request.user.is_authenticated: return '1000/m' return '100/m' ``` -------------------------------- ### Configure Django Ratelimit Middleware and Custom 429 View Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/cookbook/429.rst This snippet illustrates how to integrate `RatelimitMiddleware` into Django's `MIDDLEWARE` settings and how to specify the custom `ratelimited_error` view using the `RATELIMIT_VIEW` setting. This configuration ensures that Django Ratelimit directs rate-limited requests to the defined custom error handler, enabling proper 429 responses. ```python MIDDLEWARE = ( # ... toward the bottom ... 'django_ratelimit.middleware.RatelimitMiddleware', # ... ) RATELIMIT_VIEW = 'myapp.views.ratelimited_error' ``` -------------------------------- ### Apply Ratelimit Decorator to Entire Django Class-Based View Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Shows how to apply the `@method_decorator(ratelimit(...), name='get')` to an entire Django class-based view, specifying the method to be limited. This limits all instances of the specified method within the view. ```python @method_decorator(ratelimit(key='ip', rate='1/m', method='GET'), name='get') class MyOtherView(View): def get(self, request): pass ``` -------------------------------- ### Replace `RatelimitMixin` with `@method_decorator` and `@ratelimit` (2.0 to 3.0) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst The `RatelimitMixin` has been removed in version 3.0 as it is less powerful than the `@ratelimit` decorator. This snippet illustrates how to migrate from using `RatelimitMixin` to applying the `@ratelimit` decorator via `@method_decorator` on class-based views, allowing for more flexible rate limiting. ```python class MyView(RatelimitMixin, View): ratelimit_key = 'ip' ratelimit_rate = '10/m' ratelimit_method = 'GET' def get(self, request): pass ``` ```python class MyView(View): @method_decorator(ratelimit(key='ip', rate='10/m', method='GET')) def get(self, request): pass ``` -------------------------------- ### Define Dynamic Rate Limit with Python Callable Returning Tuple Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/rates.rst This Python function provides an alternative method for defining a dynamic rate limit. Similar to the string-returning callable, it differentiates rates based on user authentication. However, it returns the rate as a tuple of integers (count, seconds), where 1000 requests per 60 seconds are allowed for authenticated users and 100 requests per 60 seconds for unauthenticated users. ```python def my_rate_tuples(group, request): if request.user.is_authenticated: return (1000, 60) return (100, 60) ``` -------------------------------- ### Django Ratelimit Decorator by IP Address Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/security.rst This snippet illustrates the basic application of the `@ratelimit` decorator to limit requests based on the client's IP address. It's a fundamental strategy for mitigating brute-force attacks originating from a single IP address, providing a first line of defense. ```Python @ratelimit(key='ip') def login_view(request): pass ``` -------------------------------- ### APIDOC: `Ratelimited` Exception Class Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst The `Ratelimited` exception is raised when a request is blocked due to rate limiting, provided the `block` parameter is set to `True`. It is a subclass of Django's `PermissionDenied` exception. ```APIDOC ratelimit.exceptions.Ratelimited Subclass of Django's PermissionDenied exception. ``` -------------------------------- ### Update Package Imports from `ratelimit` to `django_ratelimit` (3.x to 4.0) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst The package name for django-ratelimit has changed from 'ratelimit' to 'django_ratelimit' to avoid disambiguation issues. This snippet shows the required changes for import statements when upgrading to version 4.0. ```python from ratelimit.decorators import ratelimit from ratelimit import ALL, UNSAFE ``` ```python from django_ratelimit.decorators import ratelimit from django_ratelimit import ALL, UNSAFE ``` -------------------------------- ### Django Ratelimit: Explicitly Sharing Rate Limits with 'group' (Post-0.5) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Shows how to explicitly share a rate limit across multiple views in django-ratelimit 0.5+ by using the 'group' argument in the @ratelimit decorator. Views with the same 'group', 'key', and 'rate' will share a single limit. ```Python @ratelimit(group='lists', key='user', rate='100/h') def user_list(request): pass @ratelimit(group='lists', key='user', rate='100/h') def group_list(request): pass ``` -------------------------------- ### Django Ratelimit: Sharing Limits with 'group' and Method List Order (Post-0.5) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Illustrates that views explicitly grouped using the 'group' argument will share a rate limit, even if the order of methods in the 'method' list differs, as long as the set of methods is the same. This confirms 'group's precedence in django-ratelimit 0.5+. ```Python @ratelimit(group='a', key='ip', method=['GET', 'POST'], rate='1/s') def foo(request): pass @ratelimit(group='a', key='ip', method=['POST', 'GET'], rate='1/s') def bar(request): pass ``` -------------------------------- ### APIDOC: `is_ratelimited` Function Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/usage.rst Checks if a given request should be rate-limited. This function acts as a thin wrapper around `get_usage`, providing a boolean result indicating whether the request exceeds the defined rate limit. ```APIDOC is_ratelimited(request, group=None, fn=None, key=None, rate=None, method=ALL, increment=False) request: The HTTPRequest object. group: A group of rate limits to count together. Defaults to the dotted name of the view. fn: A view function which can be used to calculate the group as if it was decorated by @ratelimit. key: What key to use, see Keys chapter. rate: '5/m' The number of requests per unit time allowed. Valid units are: s (seconds), m (minutes), h (hours), d (days). Also accepts callables. method: ALL Which HTTP method(s) to rate-limit. May be a string, a list/tuple, or None for all methods. increment: False Whether to increment the count or just check. returns: bool: Whether this request should be limited or not. ``` -------------------------------- ### Django Ratelimit: Views Not Sharing Limits Without 'group' (Post-0.5) Source: https://github.com/jsocol/django-ratelimit/blob/main/docs/upgrading.rst Highlights that views with similar but not identical @ratelimit decorator configurations (e.g., different 'method' lists without a shared 'group') will not share rate limits by default in django-ratelimit 0.5+. ```Python @ratelimit(key='ip', method=['GET', 'POST'], rate='100/h') def foo(request): pass @ratelimit(key='ip', method='GET', rate='100/h') def bar(request): pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.