Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - How to use async function based views in DRF?

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?

question from:https://stackoverflow.com/questions/65873039/how-to-use-async-function-based-views-in-drf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...