Registry / web-framework / drf-extensions

drf-extensions

JSON →
library0.8.0pypypi✓ verified 24d ago

DRF-extensions is a collection of custom extensions for Django REST Framework, designed to enhance API functionality and performance. It provides features like response caching, conditional requests, nested routes, and bulk operations. The library is actively maintained, with version 0.8.0 released recently, and it follows a regular release cadence to support newer Django and DRF versions.

pip install drf-extensions
INSTALL
IMPORT
SIG · DRF-EXTENSIONS
D
drf-extensions
web-frameworkpythonv0.8.0
Install
3.8s avg
Import
Disk
71MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.8.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 · 71.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.8s · import 0.000s · 72MB
71MB installed
● package 71MB
Code
Verified usage

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

cache_response
from rest_framework_extensions.decorators.cache import cache_response
from rest_framework_extensions.cache.decorators import cache_response

This quickstart demonstrates the `cache_response` decorator, a core feature of drf-extensions for improving API performance by caching viewset responses. Apply `@cache_response` directly to `APIView` methods to enable caching. Remember to configure Django's caching backend in your `settings.py` for production use.

import os from django.db import models from rest_framework import views, serializers, status from rest_framework.response import Response from rest_framework_extensions.cache.decorators import cache_response # --- Minimal Django setup for demonstration (not for real project) --- os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') import django if not django.apps.apps.ready: django.setup() # --- Models (if needed) --- class City(models.Model): name = models.CharField(max_length=100) population = models.IntegerField() class Meta: app_label = 'myapp' # Required for minimal setup def __str__(self): return self.name # --- Serializers (if needed) --- class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = '__all__' # --- View demonstrating caching --- class CityListView(views.APIView): @cache_response(timeout=60 * 15) # Cache for 15 minutes def get(self, request, *args, **kwargs): # In a real app, you'd fetch from DB: # cities = City.objects.all() # serializer = CitySerializer(cities, many=True) # For quickstart, simulate data: data = [ {"name": "New York", "population": 8000000}, {"name": "Los Angeles", "population": 4000000} ] return Response(data, status=status.HTTP_200_OK) # --- Example of running the view (simplified) --- # In a real Django/DRF project, this would be part of urls.py # and accessible via an HTTP request. # For demonstration, we can simulate calling the method: if __name__ == '__main__': # This part would typically be handled by Django's URL routing # and request/response cycle. # For direct execution, we're just showing the decorator effect conceptualy. print("Simulating API call with caching...") view = CityListView() # Simulate a request object minimally for the decorator class MockRequest: method = 'GET' path = '/cities/' query_params = {} # Add other attributes that might be accessed by key constructors if needed mock_request = MockRequest() response1 = view.get(mock_request) print(f"First call: {response1.data}") # A second call within the cache timeout period would ideally return cached data # (though simulating the actual cache hit without a full Django setup is complex). # The key takeaway is the decorator's placement. response2 = view.get(mock_request) print(f"Second call: {response2.data}")
Debug
Known issues
breakingVersion 0.7.0 of `drf-extensions` dropped support for Django versions below 2.2 and earlier DRF versions (specifically requiring DRF 3.9+ for 0.5.0 and DRF 3.12+ for 0.7.0). Ensure your Django and Django REST Framework versions meet the requirements when upgrading `drf-extensions` to avoid compatibility issues.
fix
Upgrade Django to 2.2+ and Django REST Framework to 3.12+ (or 3.9+ for versions before 0.7.0) before upgrading `drf-extensions`. Refer to the project's README for precise version compatibility.
affects: 0.7.0+
gotchaWhen using bulk operations (e.g., via `ListUpdateModelMixin`, `ListDestroyModelMixin`), `drf-extensions` applies changes directly to the `QuerySet`. This bypasses standard DRF serializer `save()`/`delete()` methods, viewset lifecycle hooks (`pre_save`, `post_save`, `pre_delete`, `post_delete`), and Django model signals. Any custom logic implemented in these areas will NOT be executed during bulk operations.
fix
Be aware of this behavior and implement any necessary pre/post-operation logic outside of the standard DRF/Django hooks when using bulk operations, or choose a different approach if those hooks are critical.
affects: All
gotchaFor safety and to prevent accidental mass changes, `drf-extensions` bulk destroy and bulk update operations explicitly require the `X-BULK-OPERATION` header to be present in the request. If this header is missing, the API will return a `400 BAD REQUEST` error.
fix
Always include the `X-BULK-OPERATION` header in requests for bulk update or delete actions, for example: `X-BULK-OPERATION: true`.
affects: All
gotchaWhile `drf-extensions` provides powerful caching decorators like `@cache_response`, the underlying caching mechanism relies on Django's cache framework. The default `LocMemCache` backend in Django is not suitable for production, especially in multi-process or distributed environments, as cache entries are local to each process.
fix
For production deployments, configure Django to use a robust caching backend such as Redis (`django-redis`) or Memcached in your `settings.py` to ensure consistent and scalable caching.
affects: All
Upgrade
Version history
0.8.0latest on PyPI · released Apr 10, 2025
Audit
Dependencies
djangorestframeworkrequiredCore dependency; this library extends DRF.
djangorequiredCore dependency; DRF itself depends on Django.
django-filteroptionalRequired for some filtering functionalities.
Agent activity
20 hits · last 30 days
node
18
Resources