How to use async function based views in DRF?

Viewed 10825

Since Django now supports async views, I'm trying to change my code base which contains a lot of function based views to be async but for some reason its not working.

@api_view(["GET"])
async def test_async_view(request):
    ...
    data = await get_data()
    return Response(data)

When I send a request to this endpoint, I get an error saying:

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

Does DRF not support async views yet? Is there an alternative I can do to get this working?

2 Answers

As of now, DRF doesn't support async "api views". Here is an open issue (#7260) in the DRF community and it is still in the discussion stage.

But, Django providing a decorator/wrapper which allow us to convert our sync views/function to async using sync_to_async(...) wrapper.

Example,

@sync_to_async
@api_view(["GET"])
def sample_view(request):
    data = get_data()
    return Response(data)

Note that, here, sample_view(...) and get_data(...) are sync functions.

I think you can Use this decorator in DRF

import asyncio
from functools import wraps


def to_async(blocking):
    @wraps(blocking)
    def run_wrapper(*args, **kwargs):
        return asyncio.run(blocking(*args, **kwargs))

    return run_wrapper

Example of usage

@to_async
@api_view(["GET"])
async def sample_view(request):
    ...
Related