Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hisdream86/drf-async-view
AsyncAPIView allows you to use async handlers keeping the compatibility with django-rest-framework
https://github.com/hisdream86/drf-async-view
async django django-rest-framework
Last synced: about 13 hours ago
JSON representation
AsyncAPIView allows you to use async handlers keeping the compatibility with django-rest-framework
- Host: GitHub
- URL: https://github.com/hisdream86/drf-async-view
- Owner: hisdream86
- License: mit
- Created: 2022-08-25T07:40:18.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2022-12-26T02:16:28.000Z (almost 2 years ago)
- Last Synced: 2024-09-25T16:41:27.849Z (about 2 months ago)
- Topics: async, django, django-rest-framework
- Language: Python
- Homepage:
- Size: 60.5 KB
- Stars: 18
- Watchers: 5
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# drf-async-view
Django supports [AsyncView](https://docs.djangoproject.com/en/4.1/releases/4.1/#asynchronous-handlers-for-class-based-views) from 4.1 to support writing asynchronous handlers.
`AsyncAPIView` allows you to use async handlers keeping the compatibility with django-rest-framework as well.
## Installation
You can install the latest release from pypi:
```sh
$ pip install drfasyncview
```## How to use
### Example
```python
import asynciofrom django.contrib.auth.models import User
from django.db import models
from django.http import HttpRequest, JsonResponse
from rest_framework.authentication import BaseAuthentication
from rest_framework.permissions import BasePermission
from rest_framework.throttling import BaseThrottle
from typing import Optional, Tuplefrom drfasyncview import AsyncRequest, AsyncAPIView
class AsyncAuthentication(BaseAuthentication):
async def authenticate(self, request: AsyncRequest) -> Optional[Tuple[User, str]]:
await asyncio.sleep(0.01)
return Noneclass AsyncPermission(BasePermission):
async def has_permission(self, request: AsyncRequest, view: AsyncAPIView) -> bool:
await asyncio.sleep(0.01)
return Trueclass AsyncThrottle(BaseThrottle):
async def allow_request(self, request: AsyncRequest, view: AsyncAPIView) -> bool:
await asyncio.sleep(0.01)
return Trueclass Product(models.Model):
name = models.CharField(max_length=256, unique=True)
price = models.IntegerField()class ProductsView(AsyncAPIView):
authentication_classes = [AsyncAuthentication]
permission_classes = [AsyncPermission]
throttle_classes = [AsyncThrottle]async def post(self, request: HttpRequest) -> JsonResponse:
name = request.data["name"]
price = request.data["price"]product = await Product.objects.acreate(name=name, price=price)
return JsonResponse(
data={"name": product.name, "price": product.price},
status=200,
)
```