Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to use async class based views in Django

I am trying to use the very new Django 3.1 Async view classes. Based on the limited documentation available, I have tried to create my own async def __call__() method. From the documents:

For a class-based view, this means making its __call__() method an async def (not its __init__() or as_view()).

Django 3.1 Development Documents

However, until now I have had no luck with writing an asynchronous class based view. I constantly get await exceptions, or asyncio.iscoroutinefunction returns False, which I assume should return true if the class is actually Asynchronous.

Since the documentation is lacking an example, could someone with more knowledge of async programming help me with an example of a class based asynchronous view?

like image 597
Saman Hamidi Avatar asked May 27 '20 08:05

Saman Hamidi


People also ask

How do I use async view in Django?

http import HttpResponse async def index(request): return HttpResponse("Hello, async Django!") Creating async views in Django is as simple as creating a synchronous view -- all you need to do is add the async keyword. The --reload flag tells Uvicorn to watch your files for changes and reload if it finds any.

Does Django support async views?

Django has support for writing asynchronous (“async”) views, along with an entirely async-enabled request stack if you are running under ASGI. Async views will still work under WSGI, but with performance penalties, and without the ability to have efficient long-running requests.

Should I use class-based views in Django?

Generic class-based views are a great choice to perform all these tasks. It speeds up the development process. Django provides a set of views, mixins, and generic class-based views. Taking the advantage of it you can solve the most common tasks in web development.

How do you call class-based views in Django?

Asynchronous class-based viewsimport asyncio from django. http import HttpResponse from django. views import View class AsyncView(View): async def get(self, request, *args, **kwargs): # Perform io-blocking view logic using await, sleep for example.


1 Answers

Spend quite some time searching in the Django ticket system, blogposts (thx to Joren), etc. so you don't have to.

The best you can do is using the code from the blog:

class YourView(View):    
@classonlymethod
def as_view(cls, **initkwargs):
    view = super().as_view(**initkwargs)
    view._is_coroutine = asyncio.coroutines._is_coroutine
    return view

async def get(self, *args, **kwargs):
    ...

But you also need to be aware there is no way you can use actual generics (no async ORM support, even TemplateView doesn't work) and build-in decorators for 3.1. You need to write your own stuff for things that Django normally does itself.

like image 159
Zorking Avatar answered Sep 20 '22 15:09

Zorking