Skip to main content

Async support for Django REST framework

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

adrf-0.1.12.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

adrf-0.1.12-py3-none-any.whl (20.2 kB view details)

Uploaded Python 3

File details

Details for the file adrf-0.1.12.tar.gz.

File metadata

  • Download URL: adrf-0.1.12.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.12 Darwin/24.6.0

File hashes

Hashes for adrf-0.1.12.tar.gz
Algorithm Hash digest
SHA256 e7aa49e5406b168f040f1a12cafb606e98fdd5467314240a9c42dbe63200d2c1
MD5 1458089f54bcecd0556ef741532fe7fa
BLAKE2b-256 10fe573d7ec8805aec8e13459451f81398c6ac819882496e82fb6b4ae96c2762

See more details on using hashes here.

File details

Details for the file adrf-0.1.12-py3-none-any.whl.

File metadata

  • Download URL: adrf-0.1.12-py3-none-any.whl
  • Upload date:
  • Size: 20.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.12.12 Darwin/24.6.0

File hashes

Hashes for adrf-0.1.12-py3-none-any.whl
Algorithm Hash digest
SHA256 e9d1f343b82158f4c528c0809c9635a27ceef4c37d3d8e61b8096c8eeded616d
MD5 0a3590cfe82f18486d12d1006428cc23
BLAKE2b-256 e74714006c4045f818cf625d2357e823a15b4bb7fab8dd81a40acd23af41ee53

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page