How should i write a view using Django 3 and async/await?

Hi, i’m trying to use async/await on Django 3.1. I naively tryed to write a view like:

from django.http import HttpResponse
import asyncio


async def bar(request):
    await test_1()
    return HttpResponse("Fooooooooo")


async def test_1():
    print('Hello!!')
    await asyncio.sleep(5)
    print('Bye!!')

but i’m getting an exception: 'coroutine' object has no attribute 'get'
Could you please give me some hints where too look up? (links to docs, or files in the source code? (i cloned master to see if i could find some glues, but still searching)

Django doesn’t have support for async views yet - that’s still in development in a pull request (https://github.com/django/django/pull/11650) and it’ll be a while until I can solve enough of the edge cases to get it to land.

2 Likes

@edvm Thanks to your question I was inspired to try converting my “single file Django” app to ASGI. See my new blog post: https://adamj.eu/tech/2019/09/14/a-single-file-async-django-app/

As Andrew says he hasn’t found a way to do async views yet, but you can combine Django with another framework for asynchronous paths (e.g. Websockets). See the end of my post.

Hope that helps!

1 Like

Thanks a lot @adamchainz for your mention in your blog post and the post itself (i’ll try it!)

Thank you @andrewgodwin . I’ll check it out. :ok_hand: