imbolc
imbolc

Reputation: 1833

Django 3.1 can't manage to run views asynchronously

I'm running Django-3.1 (and also I've tried master 3.2 version) in asgi mode via uvicorn. But when I open the url in a couple of browser tabs I see requests to be processed sequentially. It seems like this claim from docs:

Under a WSGI server, async views will run in their own, one-off event loop.

is also applied to ASGI mode.

Here's the code I use:

# asgi.py
import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
application = get_asgi_application()
# settings.py
SECRET_KEY = "foo"
ROOT_URLCONF = "urls"
# urls.py
import asyncio
import uuid

from django.http import HttpResponse
from django.urls import path


async def view(request):
    id = uuid.uuid4()
    print(f"{id} sleeping")
    await asyncio.sleep(5)
    print(f"{id} woke up")
    return HttpResponse("ok")


urlpatterns = [
    path("", view),
]

And here's the sequential output I see:

$ uvicorn asgi:application
INFO:     Started server process [28020]
INFO:     Waiting for application startup.
INFO:     ASGI 'lifespan' protocol appears unsupported.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
bb1d30bc-b05e-4412-94ad-f4507c766074 sleeping
bb1d30bc-b05e-4412-94ad-f4507c766074 woke up
INFO:     127.0.0.1:51878 - "GET / HTTP/1.1" 200 OK
f451d614-89dd-401d-8302-13e842040a3a sleeping
f451d614-89dd-401d-8302-13e842040a3a woke up
INFO:     127.0.0.1:51878 - "GET / HTTP/1.1" 200 OK

Upvotes: 1

Views: 767

Answers (1)

imbolc
imbolc

Reputation: 1833

Yeah, it's my bad. It's probably something to do with chrome's caching. It's enough disable it in dev-tool or send parallel requests with curl to see it working correctly.

seq 1 5 | xargs -n1 -P5  curl http://localhost:8000/

Upvotes: 1

Related Questions