Skip to main content

Async Django REST framework

Async support for Django REST framework

Requirements

  • Python 3.8+
  • Django 4.1+

We highly recommend and only officially support the latest patch release of each Python and Django series.

Installation

Install using pip...

pip install adrf

Add 'adrf' to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    ...
    'adrf',
]

Examples

Async Views

When using Django 4.1 and above, this package allows you to work with async class and function based views.

For class based views, all handler methods must be async, otherwise Django will raise an exception. For function based views, the function itself must be async.

For example:

from adrf.views import APIView

class AsyncAuthentication(BaseAuthentication):
    async def authenticate(self, request) -> tuple[User, None]:
        return user, None

class AsyncPermission:
    async def has_permission(self, request, view) -> bool:
        if random.random() < 0.7:
            return False

        return True

    async def has_object_permission(self, request, view, obj):
        if obj.user == request.user or request.user.is_superuser:
            return True

        return False

class AsyncThrottle(BaseThrottle):
    async def allow_request(self, request, view) -> bool:
        if random.random() < 0.7:
            return False

        return True

    def wait(self):
        return 3

class AsyncView(APIView):
    authentication_classes = [AsyncAuthentication]
    permission_classes = [AsyncPermission]
    throttle_classes = [AsyncThrottle]

    async def get(self, request):
        return Response({"message": "This is an async class based view."})

from adrf.decorators import api_view

@api_view(['GET'])
async def async_view(request):
    return Response({"message": "This is an async function based view."})

Async ViewSets

For viewsets, all handler methods must be async too.

views.py

from django.contrib.auth import get_user_model
from rest_framework.response import Response

from adrf.viewsets import ViewSet


User = get_user_model()


class AsyncViewSet(ViewSet):

    async def list(self, request):
        return Response(
            {"message": "This is the async `list` method of the viewset."}
        )

    async def retrieve(self, request, pk):
        user = await User.objects.filter(pk=pk).afirst()
        return Response({"user_pk": user and user.pk})

ModelViewSet Routing

The ModelViewSet implementation included with adrf provides asynchronous CRUD actions (e.g., aretrieve, acreate, aupdate, and alist). However, these actions are not invoked by default when using the router implementation in rest_framework. To have these async methods mapped by default, use adrf's router instead:

urls.py

from django.urls import path, include
from adrf import routers    # import the adrf router instead

from . import views

router = routers.DefaultRouter()
router.register(r"async_viewset", views.AsyncModelViewSet, basename="async")

urlpatterns = [
    path("", include(router.urls)),
]

Async Serializers

serializers.py

from adrf.serializers import Serializer
from rest_framework import serializers

class AsyncSerializer(Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    age = serializers.IntegerField()

views.py

from .serializers import AsyncSerializer
from adrf.views import APIView

class AsyncView(APIView):
    async def get(self, request):
        data = {
            "username": "test",
            "password": "test",
            "age": 10,
        }
        serializer = AsyncSerializer(data=data)
        serializer.is_valid()
        return await serializer.adata

Async Generics

models.py

from django.db import models

class Order(models.Model):
    name = models.TextField()

serializers.py

from adrf.serializers import ModelSerializer
from .models import Order

class OrderSerializer(ModelSerializer):
    class Meta:
        model = Order
        fields = ('name', )

views.py

from adrf.generics import ListCreateAPIView
from .models import Order
from .serializers import OrderSerializer

class ListCreateOrderView(ListCreateAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

Metadata

Release files for adrf 0.1.14

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for adrf 0.1.14
File Size Uploaded
adrf-0.1.14.tar.gz 19.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for adrf 0.1.14
File Interpreter ABI Platform
adrf-0.1.14-py3-none-any.whl Python 3 none any Details

Total release size: 42.0 kB

Release files / adrf-0.1.14.tar.gz

Download URL adrf-0.1.14.tar.gz
Size 19.3 kB
Tags Source
SHA-256 checksum
How to use checksums
c6ded6771a4a2a65c8dad3d3bf027cf0bb7b01025f8e9dff18c9a58920edeac6
BLAKE2b-256 checksum
How to use checksums
adf32e4647d679c1c3cb8f7316eabc85d4fafe396318a5aa389f2ef14a2df103
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.12.12 Darwin/25.5.0

Release files / adrf-0.1.14-py3-none-any.whl

Download URL adrf-0.1.14-py3-none-any.whl
Size 22.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dcf03cb6fbeb5d37dcb819740c17dd40db36481bbbb049f9fa8f39675747607b
BLAKE2b-256 checksum
How to use checksums
38309c482ba6256b0c4b57a4ad6a5da918f57064689d0d3d9595515707222ff9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/2.2.1 CPython/3.12.12 Darwin/25.5.0

Release history Release notifications | RSS feed

This release

0.1.14 This release

2 release files

0.1.13

2 release files

0.1.12

2 release files

0.1.11

2 release files

0.1.10

2 release files

0.1.9

2 release files

0.1.8

2 release files

0.1.7

2 release files

0.1.6

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page