9

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?

3
  • 1
    Could you post a code example of what you've tried? Commented Jul 28, 2020 at 14:17
  • 1
    medium.com/@bruno.fosados/… Commented Aug 5, 2020 at 1:10
  • Is there any example where I can see async __call__() method? Commented Jan 27, 2021 at 7:50

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

When I called the API with a different method (say PUT/POST) instead of raising 405 Method Not Allowed, It responded with 500 - TypeError: object HttpResponseNotAllowed can't be used in 'await' expression I'm not sure how to fix this. Can you please help me with this? Thanks in advance.
I get You cannot call this from an async context - use a thread or sync_to_async.
1
class Test(CreateView):
    template_name = 'index.html'
    form_class = TestForm
    view_is_async = True # on async

1 Comment

This answer is wrong. It may look like it is working but it can cause problems. view_is_async is a property that depends on many things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.