AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`

I follow the instruction posted here

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.

I have started the application using dyphne and define it in settings.py

INSTALLED_APPS = [
    'daphne',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'chat',
    'oauth',
    'corsheaders',
    'rest_framework',
]
ASGI_APPLICATION = 'sample.asgi.application'

and wrap my views with async def with something like

@api_view(['GET', 'POST'])
@authentication_classes([SessionAuthentication])
@permission_classes([IsAuthenticated]) 
async def sessions(request):
    if request.method == 'GET':
        user = request.user  
        sessions = [session async for session in Session.objects.filter(user=user)]
        return JsonResponse(SessionSerializer(sessions,many=True).data, safe=False)
    elif request.method == 'POST':
        user = request.user
        session = await Session.objects.acreate(name='new session', user=user)
        return JsonResponse(SessionSerializer(session).data)

I have set everything up and it shows it runs under asgi correctly

Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP/2 support not enabled (install the http2 and tls Twisted extras)

But It just panics with

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'coroutine'>`

Do i miss something to be configured here? :upside_down_face:

1 Like

I’ve solved problem by changing api_view from rest_framework.decorators.apiview to ardf.decorators.apiview

Hi, whats ardf, and how you install it ?

Its a custom package made by em1208 on github, and its not ardf but adrf. You can install it with pip install adrf.