DRF-extensions

0.8.0 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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}")

view raw JSON →