From version 3.1 Django supports async views. I have a Django app running on uvicorn. I'm trying to write an async view, which can handle multiple requests to itself concurrently, but have no success.
Common examples, I've seen, include making multiple slow I/O operations from inside the view:
async def slow_io(n, result): await asyncio.sleep(n) return result async def my_view(request, *args, **kwargs): task_1 = asyncio.create_task(slow_io(3, 'Hello')) task_2 = asyncio.create_task(slow_io(5, 'World')) result = await task_1 + await task_2 return HttpResponse(result) This will yield us "HelloWorld" after 5 seconds instead of 8 because requests are run concurrently.
What I want - is to concurrently handle multiple requests TO my_view. E.g. I expect this code to handle 2 simultaneous requests in 5 seconds, but it takes 10.
async def slow_io(n, result): await asyncio.sleep(n) return result async def my_view(request, *args, **kwargs): result = await slow_io(5, 'result') return HttpResponse(result) I run uvicorn with this command:
uvicorn --host 0.0.0.0 --port 8000 main.asgi:application --reload Django doc says:
The main benefits are the ability to service hundreds of connections without using Python threads.
So it's possible.
What am I missing?
UPD: It seems, my testing setup was wrong. I was opening multiple tabs in browser and refreshing them all at once. See my answer for details.