Chapter 53 · Async Django, ASGI, and sync/async boundariesCHAPTER 53
Complete six-part pre-release for review. Django moves to 6.1.3, a security release; daphne is added, and uvicorn for development. Timings are from one Windows 11 laptop. A real partner over TLS and a production server were not checked.
Working towards: API and integrations (Chapter 54). Another program can list published events through an API and receive signed notifications when an event changes. All milestones
CHAPTER FIFTY-THREE
Async Django, ASGI, and sync/async boundaries
Stage 6: APIs and real-time updates (Chapters 47 to 54)
Prerequisites: Chapters 9 to 52, including the Chapter 52 project with its 772 passing tests, the Webhooks page with the library’s endpoint and examples/receiver.py, the streamed attendee download of Chapter 41, and the three middleware classes of Chapters 23, 39, and 50
What you’ll build: Otahque on Django 6.1.3, served in development by Daphne’s ASGI runserver; middleware that runs without a thread on either kind of server; a Send test button on each webhook endpoint, an async view that waits for the partner without holding Django to a sync path; an attendee download that streams under ASGI; and a measurement of what async changed, with the numbers and the machine
Why This Matters
The library has added its endpoint, and the administrator wants to know it works before Raj next cancels an event. Today the only way is to publish something and wait for the worker. A Send test button on the endpoint’s page would answer at once: signed like a real message, sent now, the partner’s answer shown. But the partner is another server on the internet. It may answer in a fifth of a second or take the full 15 seconds Chapter 52 allows, and the request that asked has nothing to do but wait.
Waiting is what async code is for. Python’s async and await let one thread start many waits and pick each up when its answer arrives, and Django has supported async views since version 3.1. It is also the topic most often oversold. Async Django does not make a page faster. Django’s ORM is synchronous, so async code reaches the database through a thread. A server must speak ASGI, not WSGI, to run it as intended. And one sync-only middleware class makes every request change threads twice. This chapter moves Otahque onto ASGI, finds every place that boundary runs through Otahque’s code, and measures, rather than assumes, what changed.
There is a second reason to move now. Chapter 54 sends live updates to open pages over WebSockets, which only an ASGI server can hold, and Chapter 62 chooses an ASGI server for production. Two things change in this chapter because of that: Otahque’s download of attendees, which streams under WSGI but would be built whole first under ASGI, and the server you start every day.
By the end of the chapter, you will be able to:
explain the difference between WSGI and ASGI, and what Django does with sync and async code under each;
run Otahque under Daphne’s runserver and, once, under uvicorn, and say why one serves the stylesheet and the other does not;
write an async view, reach the ORM from it correctly, and recognize SynchronousOnlyOperation;
make middleware and decorators that keep an async view async;
stream a response under ASGI with an async generator, and stop it when the client leaves;
measure a sync and an async view against a slow partner, and explain the result honestly.
Out of scope: WebSockets and live pages (Chapter 54), the production server and its process manager (Chapter 62), serving static files without runserver (Chapter 63), database connection pooling (Chapter 57), and converting the rest of Otahque to async, which this chapter argues against.
A request to the partner spends almost all its time waiting: for the name to resolve, the connection to open, and the answer to come back. The computer does almost nothing meanwhile. Concurrency means having several tasks in progress at once, taking turns; parallelism means running several at the same instant on different processor cores. Waiting needs only concurrency.
Django has always handled concurrent requests with threads: the server gives each request a thread, and a thread that waits on the network simply sleeps until the operating system wakes it. That works, and Otahque has used it since Chapter 6. Each thread costs memory and a slot in a pool, though, and a request stuck in a 15-second wait holds its thread the whole time.
New Concept: async code and the event loo
What problem exists? Many tasks spend most of their time waiting, and a thread per waiting task is a heavy way to wait.
What did people do before? More threads or processes, or callbacks that are hard to read and harder to cancel.
What is it? In Python, an async def function is a coroutine. Where it must wait, it writes await, which hands control back to an event loop (from the standard library’s asyncio). The loop runs other coroutines meanwhile and resumes this one when its answer arrives. One thread can keep hundreds of waits in progress this way.
Why use it? For work that is mostly waiting on other servers, and for connections that stay open, such as WebSockets.
Now let’s use it. Step 8 writes an async view, and Step 11 measures what it changed.
The catch is that every wait must be an await. A plain sync call inside a coroutine, such as httpx.post() or a database query, stops the whole loop, and every other coroutine on it, until it returns. Figure 53.1 shows the two ways of waiting side by side.
Figure 53.1 — Waiting with a thread each, and waiting on one event loop.
WSGI and ASGI
A Python web server and a Django project meet at one interface. Since 2003 that has been WSGI: the server calls the project once per request, as a plain function, and waits for the response. It has no way to await anything, and no way to keep a connection open after the response. ASGI is its successor: the server awaits the project as a coroutine, passes events in and out, and can keep a connection open for as long as both sides want. Django ships both entry points, config/wsgi.py and config/asgi.py, made by startproject in Chapter 6; Otahque has used only the first.
New Concept: ASG
What problem exists? WSGI cannot await, and cannot hold a connection open after a response.
What did people do before? A separate server for long connections beside the WSGI one.
What is it? The Asynchronous Server Gateway Interface, a specification for how an async Python server talks to an application. Django’s config/asgi.py returns an ASGI application; Daphne, uvicorn, Hypercorn, and Granian are ASGI servers.
Why use it? Async views run on the server’s event loop, a disconnecting client cancels its request, and Chapter 54’s WebSockets become possible on the same server.
Now let’s use it. Step 3 serves Otahque with Daphne; Step 4 with uvicorn.
Django runs both kinds of view under both kinds of server, and adapts where they differ. Under WSGI, an async view gets an event loop of its own for that one request, which works and gains nothing. Under ASGI, a sync view runs in a thread, so it cannot block the loop. Figure 53.2 sets the two side by side.
Figure 53.2 — WSGI and ASGI side by side.
Daphne, and the runserver you already use
runserver serves WSGI. Several ASGI servers can replace it for development; Daphne, maintained by the Django project alongside Channels, does it most quietly: put daphne first in INSTALLED_APPS, name the application in ASGI_APPLICATION, and the same runserver command starts Daphne instead, keeping the reloader and the static files that development relies on (N53.3). uvicorn, a popular ASGI server, is run once in Step 4 to show that Otahque does not depend on the server; it serves no static files, a difference Chapter 63 deals with for production.
New Tool: Daphne 4.2.
What problem exists? Development should run Otahque the way production will, under ASGI, with the command readers already know.
What did people do before? A different command for the ASGI server, and Django’s WSGI runserver for everything else.
What is it? An ASGI server built on Twisted, maintained alongside Django Channels. With daphne first in INSTALLED_APPS, it provides Otahque’s runserver.
Why Daphne? Same command, reloader, and static files as before; and Chapter 54’s Channels is built to run on it.
Now let’s use it. Step 3 adds it and starts the server.
Where sync meets async
Otahque is, and stays, mostly sync code: its views, forms, model methods, and templates are plain functions, and that is fine. Django draws the boundary for you in most places. You draw it in three:
The ORM from async code. A query run directly in a coroutine would block the loop, so Django refuses it with SynchronousOnlyOperation. Use the async methods, such as aget(), acreate(), acount(), afirst(), and async for over a queryset, or hand a sync function to a thread with sync_to_async(). Transactions do not yet work in async mode in Django 6.1, so any write that needs atomic() stays in a sync function called through sync_to_async().
Middleware. Each class says whether it can run sync, async, or both. A sync-only class in an ASGI stack makes Django switch to a thread before it and back after it, on every request. Three of Otahque’s own classes are sync-only.
Decorators. A decorator that wraps a view in a plain function turns an async view back into a sync one, and Django then receives an unawaited coroutine where it expects a response. Django’s own login_required, permission_required, require_POST, and never_cache handle both kinds; allauth’s reauthentication_required and Otahque’s webhooks_access do not.
Under the Hood: the threads Django keeps under ASG
Django’s ASGI handler wraps each request in a ThreadSensitiveContext, from asgiref. Any sync code that runs during the request with sync_to_async(thread_sensitive=True), the default, runs in one thread that belongs to that request, so sync code that expects to stay on one thread, such as a database connection, always does. Django itself has sync code in every request: the request_started and request_finished signals reset the query log and close stale database connections, so even a request to an async view gets its own thread for those few moments. While an async view awaits a partner, that thread sits idle instead of blocked. Error pages are different: when an async view raises an exception, such as PermissionDenied, Django builds the error page with thread_sensitive=False, in a thread outside the request’s, which matters for any query the page makes (Step 8). And CONN_MAX_AGE, which keeps database connections between requests, must stay at its default of 0 under ASGI; Otahque never set it, and Chapter 57 looks at pooling instead.
Each place the boundary runs through Otahque after this chapter is marked in Figure 53.3.
Figure 53.3 — Where sync and async meet in Otahque.
Streaming under ASGI
Chapter 41’s download is a StreamingHttpResponse fed by a generator, so a list of thousands of attendees goes out a few rows at a time. Under WSGI the server pulls from a sync generator. Under ASGI it pulls with async for, and a sync generator cannot be pulled that way: Django reads it to the end first, holds the whole file in memory, and warns “StreamingHttpResponse must consume synchronous iterators in order to serve them asynchronously.” The download still works, but no longer streams. Step 10 makes it an async generator, an async def function that yields, so it streams again, and stops when the client goes away.
What async does not do
Async changes how a server waits. It does not make a database query, a template, or a Python loop run faster, and for a page that mostly reads the database, a sync view under a threaded server is just as quick and simpler. Converting all of Otahque would add sync_to_async() around most of its code for no gain. So this chapter converts two views, the one whose work is waiting on another server and the one whose work is a long stream, and makes the shared parts, middleware and decorators, ready for both. Step 11 then measures one claim most tutorials make, that async views serve slow calls faster, against a slow partner on one laptop.
In practice: a partner’s slow endpoin
Situation. The library’s receiver runs on a small server that takes eight seconds to answer while it restarts, and the administrator presses Send test twice in a row.
Application. Each press waits up to 15 seconds in an async view; the card then shows the answer, or the timeout, and how long it took. If the administrator closes the tab, the view is cancelled and the outbound connection closed.
Consideration. The administrator still waits: async frees the server, not the person. A message that may take long belongs in the background, as Chapter 52’s real messages are; Send test is the one place a person asked to watch.
Start from Chapter 52, in the folder containing manage.py, with Otahque on PostgreSQL 18, 772 passing tests, the library’s endpoint on the Webhooks page, and the work committed (the last commit is “Tell partners of changes with webhooks”). Three packages change: Django moves to 6.1.3, a security release; daphne 4.2.3 is added; and uvicorn 0.55.0 is added for development. One migration is new, in integrations. The settings, the three custom middleware classes and the time zone helper, the integrations models, form, views, addresses, and endpoint page, the download’s view and table, the example receiver, the stylesheet and site.js, pyproject.toml, and the API contract change. New: integrations/trial.py, three test modules, and two scripts in examples/. The visible result: runserver says it is Daphne; an endpoint’s page has a Send test button whose answer appears on the page; and the attendee download streams under ASGI. The commands were checked in Windows PowerShell 5.1 and Git Bash against PostgreSQL 18.
The Custom Way
Without async, the usual way to stop a slow call holding a request is to hand it to a thread of your own:
The administrator gets the page back at once, and never sees the answer, which was the point of the button. The thread has no timeout of its own and nothing stops it if the server restarts. It uses a database connection that Django does not know to close. Nothing cancels it if nobody is waiting any more. And under a server that runs many processes, nobody can tell which one holds it. This illustration is not added to the project.
The Django Way
The Django Way keeps the request, and the administrator, waiting for the answer, but waits without holding Django to a sync path: an async view, on an ASGI server, awaiting httpx’s async client. The sync parts it needs, the address check and the audit record, run in a thread through sync_to_async(), and the database is reached with Django’s async query methods.
Step 1: Check the starting point
Terminal
uv run python manage.py test --parallel
Output
Found 772 test(s).
Creating test database for alias 'default'...
...
Ran 772 tests in ...s
OK
Terminal
git status --short
git log --oneline -1
Output
... Tell partners of changes with webhooks
Step 2: Django 6.1.3, a security release
Django 6.1.3 came out on 3 November 2026 with fixes for six security issues, one rated moderate: a file uploaded in base64 could make MultiPartParser use unbounded memory, and Otahque has accepted uploads since Chapter 42. A patch release changes no behaviour a project relies on, so the book moves to it here as its own step, with the whole suite as the check (N-V).
Terminal
uv add django==6.1.3
Output
Resolved 63 packages in ...
Uninstalled 1 package in ...
Installed 1 package in ...
- django==6.1.2
+ django==6.1.3
While pyproject.toml is open: Chapter 52 added the integrations app but not to the apps coverage measures (Chapter 32). Its [tool.coverage.run] list becomes:
Daphne brings Twisted, the networking library it is built on, and a few packages of its own. In config/settings.py, put it first in INSTALLED_APPS, so its runserver command replaces Django’s:
config/settings.py
INSTALLED_APPS = [
# Chapter 53: first, so its runserver, an ASGI server,
# replaces Django's WSGI one.
'daphne',
'django.contrib.admin',
and name the application it serves, beside the WSGI one:
config/asgi.py itself is unchanged since Chapter 6. Start the server as always:
Terminal
uv run python manage.py runserver
Folder structure
System check identified no issues (0 silenced).
December 2, 2026 - ...
Django version 6.1.3, using settings 'config.settings'
Starting ASGI/Daphne version 4.2.3 development server at
http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
HTTP GET / 200 [..., 127.0.0.1:...]
HTTP GET /events/ 200 [..., 127.0.0.1:...]
HTTP GET /static/otahque/site.css 200 [..., 127.0.0.1:...]
“Starting ASGI/Daphne” replaces “Starting development server”. Open http://127.0.0.1:8000/events/: the page and its stylesheet load as before, and the reloader still restarts the server when a file changes. Stop it with Ctrl+C. From now on, every runserver in the book is Daphne’s.
Common Error: Daphne after Django’s own app
If daphne is not first in INSTALLED_APPS, django.contrib.staticfiles’ runserver is found first and the server still says “Starting development server”: WSGI, as before. Move daphne to the top. If it stops with “Cannot find ASGI_APPLICATION setting.”, add the setting above.
Step 4: The same application on uvicorn
Daphne is not the only ASGI server, and Otahque should not depend on one. Add uvicorn, for development only:
Terminal
uv add --dev uvicorn==0.55.0
Output
Resolved 82 packages in ...
Installed 2 packages in ...
+ click==8.5.1
+ uvicorn==0.55.0
and run Otahque’s ASGI application with it:
Terminal
uv run uvicorn config.asgi:application
Output
INFO: Started server process [...]
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)
INFO: 127.0.0.1:... - "GET / HTTP/1.1" 200 OK
INFO: 127.0.0.1:... - "GET /events/ HTTP/1.1" 200 OK
INFO: 127.0.0.1:... - "GET /static/otahque/site.css
HTTP/1.1" 404 Not Found
The events page answers 200 and is unstyled: /static/otahque/site.css answers 404. Serving files from static/ is something runserver does for development, and uvicorn is a plain ASGI server that knows nothing about Django’s static files. In production a web server or WhiteNoise serves them (Chapter 63). The application itself is the same config.asgi:application Daphne serves. The line about the lifespan protocol is uvicorn noticing that Django does not answer ASGI’s start-up and shut-down events; Step 7 comes back to what that means. Stop uvicorn with Ctrl+C; the book keeps Daphne’s runserver for daily work (N53.3).
Step 5: Async code meets the ORM
Before writing an async view, see the boundary for yourself. Create examples/boundary.py:
examples/boundary.py
"""Async code meets the ORM (Chapter 53).
Not part of Otahque: run it once to see the boundary.
uv run python examples/boundary.py
It counts events three ways from inside a coroutine: the
plain sync query, which Django refuses, then the async
query, then the sync query handed to a thread.
"""
import asyncio
import os
import sys
import textwrap
from pathlib import Path
import django
from asgiref.sync import sync_to_async
from django.core.exceptions import SynchronousOnlyOperation
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'config.settings')
django.setup()
from events.models import Event # noqa: E402
async def main():
"""Try each way and print what happens."""
try:
Event.objects.count()
except SynchronousOnlyOperation as error:
print('count():', type(error).__name__)
print(textwrap.fill(str(error), 60,
initial_indent=' ',
subsequent_indent=' '))
print('acount():', await Event.objects.acount())
count = sync_to_async(Event.objects.count)
print('sync_to_async(count)():', await count())
asyncio.run(main())
Terminal
uv run python examples/boundary.py
Output
count(): SynchronousOnlyOperation
You cannot call this from an async context - use a thread
or sync_to_async.
acount(): 14
sync_to_async(count)(): 14
The plain query is refused before it reaches the database; acount() and the query handed to a thread both work. Django’s refusal protects the event loop: a query run inside a coroutine would stop every other coroutine until it returned. Do not silence it with the DJANGO_ALLOW_ASYNC_UNSAFE environment variable, which exists for notebooks, not for servers.
Step 6: Middleware for both kinds of server
Under ASGI, Django builds the middleware chain to suit each class. A class with async_capable = True gets an async get_response and is awaited directly; a sync-only class gets a sync one, and Django switches to a thread before it and back after it, on every request. All of Django’s and the third-party classes in Otahque’s MIDDLEWARE handle both. Three of Otahque’s own do not: the request id (Chapter 39), the viewer’s time zone (Chapter 23), and the API token’s reset (Chapter 50). The test first, in config/tests/test_async.py:
config/tests/test_async.py
"""Otahque's middleware under ASGI (Chapter 53)."""
from asgiref.sync import iscoroutinefunction
from django.conf import settings
from django.http import HttpResponse
from django.test import RequestFactory, SimpleTestCase, TestCase
from django.utils import timezone
from django.utils.module_loading import import_string
from accounts.middleware import TimezoneMiddleware
from accounts.models import Profile
from audit.middleware import CredentialMiddleware
from audit.models import acting_token
from config.helpers import in_group
from config.middleware import RequestIDMiddleware, current_id
async def zone_and_id(request):
"""Answer with the zone and the request id in use."""
return HttpResponse(
f'{timezone.get_current_timezone_name()} '
f'{current_id.get()} {acting_token.get()}')
class MiddlewareTests(SimpleTestCase):
"""Every class in MIDDLEWARE can run without a thread."""
def test_every_class_is_async_capable(self):
sync_only = [
path for path in settings.MIDDLEWARE
if not getattr(import_string(path),
'async_capable', False)
]
self.assertEqual(sync_only, [])
def test_an_async_chain_stays_async(self):
for kind in (RequestIDMiddleware, TimezoneMiddleware,
CredentialMiddleware):
with self.subTest(kind.__name__):
self.assertTrue(iscoroutinefunction(
kind(zone_and_id)))
class AsyncPathTests(TestCase):
"""Each class's async path does what its sync one does."""
@classmethod
def setUpTestData(cls):
cls.sai = in_group('sai@example.org', 'Organizers')
profile = Profile.of(cls.sai)
profile.timezone = 'Asia/Kolkata'
profile.save()
def request(self, user):
"""Return a GET request whose auser() answers user."""
request = RequestFactory().get('/events/')
async def auser():
return user
request.auser = auser
return request
async def test_the_id_reaches_the_view_and_header(self):
chain = RequestIDMiddleware(zone_and_id)
response = await chain(self.request(self.sai))
seen = response.content.decode().split()[1]
self.assertEqual(seen, response['X-Request-ID'])
self.assertEqual(current_id.get(), '-')
async def test_the_profile_zone_is_read_with_await(self):
chain = TimezoneMiddleware(zone_and_id)
response = await chain(self.request(self.sai))
zone = response.content.decode().split()[0]
self.assertEqual(zone, 'Asia/Kolkata')
async def test_no_token_is_carried_in(self):
# Reset here, in this coroutine: asgiref copies a
# test's context back, so a value left set would
# reach later tests.
reset = acting_token.set('left over')
try:
chain = CredentialMiddleware(zone_and_id)
response = await chain(self.request(self.sai))
self.assertTrue(
response.content.endswith(b' None'))
self.assertEqual(acting_token.get(), 'left over')
finally:
acting_token.reset(reset)
test_every_class_is_async_capable reads MIDDLEWARE itself, so a sync-only class added in a later chapter fails it at once. The other tests call each class’s async path with an async inner handler, as Chapter 39’s test called the sync path.
Terminal
uv run python manage.py test config.tests.test_async
Output
Found 5 test(s).
Creating test database for alias 'default'...
ERROR: test_the_id_reaches_the_view_and_header
TypeError: 'coroutine' object does not support item
assignment
ERROR: test_the_profile_zone_is_read_with_await
AttributeError: 'WSGIRequest' object has no attribute 'user'.
Did you mean: 'auser'?
FAIL: test_an_async_chain_stays_async [CredentialMiddleware]
AssertionError: False is not true
FAIL: test_an_async_chain_stays_async [RequestIDMiddleware]
AssertionError: False is not true
FAIL: test_an_async_chain_stays_async [TimezoneMiddleware]
AssertionError: False is not true
FAIL: test_every_class_is_async_capable
AssertionError: Lists differ:
['config.middleware.RequestIDMiddleware', [77 chars]are']
!= []
FAIL: test_no_token_is_carried_in
AssertionError: False is not true
Ran 5 tests in ...s
FAILED (failures=5, errors=2)
test_every_class_is_async_capable lists the three classes, shortened by unittest to fit. The others show what a sync-only class does with an async handler: it calls the handler, gets a coroutine back instead of a response, and tries to set a header on it.
Django’s documented pattern for a class that serves both: say so with sync_capable and async_capable; in __init__, find out which kind of get_response it was given; and if it is async, mark the instance as a coroutine function with markcoroutinefunction(), so Django awaits it. __call__ then sends an async request to __acall__. Replace config/middleware.py:
config/middleware.py
"""Middleware for the whole project (Chapter 39)."""
import logging
import uuid
from contextvars import ContextVar
from asgiref.sync import (
iscoroutinefunction, markcoroutinefunction,
)
# The id of the request being handled, read by log records.
current_id = ContextVar('request_id', default='-')
class RequestIDMiddleware:
"""Give each request an id, for its page and its logs.
The id goes on the request, into the X-Request-ID
header, and into log records. It is always new: an id
a browser sends is not trusted until our own proxy
sets it (Chapter 63).
"""
# Chapter 53: one class for both kinds of server. Under
# ASGI, Django hands it an async get_response and calls
# it without a thread in between.
sync_capable = True
async_capable = True
def __init__(self, get_response):
"""Keep the next handler; match its kind."""
self.get_response = get_response
self.is_async = iscoroutinefunction(get_response)
if self.is_async:
markcoroutinefunction(self)
def __call__(self, request):
"""Set the id, call the rest, then add the header."""
if self.is_async:
return self.__acall__(request)
token = current_id.set(new_id(request))
try:
response = self.get_response(request)
finally:
current_id.reset(token)
response['X-Request-ID'] = request.id
return response
async def __acall__(self, request):
"""Do the same, awaiting the rest of the chain."""
token = current_id.set(new_id(request))
try:
response = await self.get_response(request)
finally:
current_id.reset(token)
response['X-Request-ID'] = request.id
return response
def new_id(request):
"""Give request a new id; return it."""
request.id = uuid.uuid4().hex
return request.id
class RequestIDFilter(logging.Filter):
"""Add request_id to each log record a handler sees."""
def filter(self, record):
"""Copy the current id onto the record; keep it."""
record.request_id = current_id.get()
return True
and audit/middleware.py:
audit/middleware.py
"""Middleware for the audit trail (Chapter 50)."""
from asgiref.sync import (
iscoroutinefunction, markcoroutinefunction,
)
from .models import acting_token
class CredentialMiddleware:
"""Forget the request's token when the request ends.
The API's authentication sets acting_token; without
this, the next request on the same thread would be
recorded as made with that token.
"""
sync_capable = True
async_capable = True
def __init__(self, get_response):
"""Keep the next handler; match its kind (53)."""
self.get_response = get_response
self.is_async = iscoroutinefunction(get_response)
if self.is_async:
markcoroutinefunction(self)
def __call__(self, request):
"""Start with no token; restore the old value after."""
if self.is_async:
return self.__acall__(request)
reset = acting_token.set(None)
try:
return self.get_response(request)
finally:
acting_token.reset(reset)
async def __acall__(self, request):
"""Do the same, awaiting the rest of the chain."""
reset = acting_token.set(None)
try:
return await self.get_response(request)
finally:
acting_token.reset(reset)
Context variables, such as current_id and acting_token, work in both: a coroutine and the threads sync_to_async() starts for it see the same values. The time zone needs more care, because it reads the member’s profile from the database. In accounts/middleware.py, the imports become:
accounts/middleware.py
"""Middleware for the viewer's zone and for sign-in."""
from asgiref.sync import (
iscoroutinefunction, markcoroutinefunction,
)
from django.contrib.auth import middleware
from django.contrib.auth.views import redirect_to_login
from django.shortcuts import resolve_url
from django.urls import reverse
from django.utils import timezone
from django_htmx.http import HttpResponseClientRedirect
from .timezones import aresolve_timezone, resolve_timezone
and the class becomes:
accounts/middleware.py
class TimezoneMiddleware:
"""Show every page in the viewer's zone.
The admin is the exception: it stays in UTC (Chapter 23).
"""
sync_capable = True
async_capable = True
def __init__(self, get_response):
"""Keep the next handler; match its kind (53)."""
self.get_response = get_response
self.is_async = iscoroutinefunction(get_response)
if self.is_async:
markcoroutinefunction(self)
def __call__(self, request):
"""Turn on the viewer's zone for this request."""
if self.is_async:
return self.__acall__(request)
if in_admin(request):
timezone.deactivate()
else:
timezone.activate(resolve_timezone(request))
return self.get_response(request)
async def __acall__(self, request):
"""Do the same, reading the profile with await."""
if in_admin(request):
timezone.deactivate()
else:
timezone.activate(
await aresolve_timezone(request))
return await self.get_response(request)
def in_admin(request):
"""Return whether request is for the admin."""
return request.path.startswith(reverse('admin:index'))
In accounts/timezones.py, resolve_timezone() gains an async twin. Both share the query and the cookie, so they cannot drift apart:
accounts/timezones.py
def resolve_timezone(request):
"""Return the zone to show times in.
The member's profile, then the browser's cookie,
then UTC.
"""
user = request.user
if user.is_authenticated:
saved = saved_zones(user).first()
if saved:
return ZoneInfo(saved)
return cookie_zone(request)
async def aresolve_timezone(request):
"""Return the same zone, from async code (Chapter 53).
auser() and afirst() wait for the database without
holding the event loop.
"""
user = await request.auser()
if user.is_authenticated:
saved = await saved_zones(user).afirst()
if saved:
return ZoneInfo(saved)
return cookie_zone(request)
def saved_zones(user):
"""Return a query for the zone in user's profile."""
return Profile.objects.filter(
user=user
).values_list('timezone', flat=True)
def cookie_zone(request):
"""Return the browser cookie's zone, or UTC."""
name = request.COOKIES.get(COOKIE, '')
if name in KNOWN:
return ZoneInfo(name)
return UTC
request.auser() is the async way to read the signed-in member; request.user would query the database the sync way, and Django would refuse it, as in Step 5.
Terminal
uv run python manage.py test config.tests.test_async
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Step 7: A test message
Send test’s message is a WebhookDelivery of a new type, webhook.test, so it appears in the endpoint’s log beside real messages (D53.1). It is signed and sent like them, with Chapter 52’s address rules and 15-second limit, but it is sent once and never retried, its status is Sent or Failed, never Queued, and a failure does not count toward the 20 failures that turn an endpoint off. The tests come first, in integrations/tests/test_trial.py:
integrations/tests/test_trial.py
"""Send test: one signed message, at once (Chapter 53)."""
import asyncio
from unittest import mock
import httpx
from django.test import TestCase
from standardwebhooks import Webhook
from integrations import trial
from integrations.models import WebhookDelivery
from integrations.tests.helpers import endpoint, resolving_to
Status = WebhookDelivery.Status
class TrialTests(TestCase):
"""What a test message sends, and what it records."""
@classmethod
def setUpTestData(cls):
cls.hook = endpoint()
def answering(self, handle):
"""Play the partner with handle, an async function."""
patch = mock.patch.object(
trial, 'transport', httpx.MockTransport(handle))
patch.start()
self.addCleanup(patch.stop)
async def test_a_signed_message_once(self):
seen = []
async def handle(request):
seen.append(request)
return httpx.Response(204)
self.answering(handle)
with resolving_to('93.184.215.14'):
delivery = await trial.send(self.hook)
self.assertEqual(len(seen), 1)
sent = seen[0]
Webhook(self.hook.secret).verify(sent.content,
dict(sent.headers))
self.assertEqual(sent.headers['host'],
'library.example')
self.assertEqual(delivery.kind, 'webhook.test')
self.assertEqual(delivery.status, Status.SENT)
self.assertEqual(delivery.attempts, 1)
self.assertEqual(delivery.last_code, 204)
async def test_a_failure_is_final(self):
async def handle(request):
return httpx.Response(500, text='Down for repairs')
self.answering(handle)
with resolving_to('93.184.215.14'):
delivery = await trial.send(self.hook)
self.assertEqual(delivery.status, Status.FAILED)
self.assertEqual(delivery.reply, 'Down for repairs')
await self.hook.arefresh_from_db()
self.assertEqual(self.hook.failures_in_a_row, 0)
async def test_an_inner_address_is_never_called(self):
async def handle(request):
raise AssertionError('called')
self.answering(handle)
with resolving_to('10.0.0.5'):
delivery = await trial.send(self.hook)
self.assertEqual(delivery.status, Status.FAILED)
self.assertIn('may not call', delivery.last_error)
async def test_a_timeout_is_a_failure(self):
async def handle(request):
raise httpx.ReadTimeout('no answer', request=request)
self.answering(handle)
with resolving_to('93.184.215.14'):
delivery = await trial.send(self.hook)
self.assertEqual(delivery.status, Status.FAILED)
self.assertTrue(delivery.last_error.startswith(
'ReadTimeout'))
async def test_leaving_early_closes_the_call(self):
started, closed = asyncio.Event(), asyncio.Event()
async def handle(request):
started.set()
try:
await asyncio.sleep(10)
finally:
closed.set()
self.answering(handle)
with resolving_to('93.184.215.14'):
sending = asyncio.create_task(
trial.send(self.hook))
await started.wait()
sending.cancel()
with self.assertRaises(asyncio.CancelledError):
await sending
self.assertTrue(closed.is_set())
self.assertFalse(await WebhookDelivery.objects.filter(
kind='webhook.test').aexists())
The partner is played by an httpx.MockTransport with an async handler, so nothing leaves the computer. The last test cancels the sending task while the partner is still answering, as Django does when a browser goes away, and checks that the outbound call was closed and no row was left behind.
Terminal
uv run python manage.py test integrations.tests.test_trial
Output
Found 1 test(s).
ERROR: test_trial (unittest.loader._FailedTest.test_trial)
ImportError: Failed to import test module: test_trial
ImportError: cannot import name 'trial' from 'integrations'
(...\integrations\__init__.py)
Ran 1 test in ...s
FAILED (errors=1)
In integrations/models.py, the kinds gain the test type, and the three kinds an endpoint may ask for get a name of their own:
integrations/models.py
class Kind(models.TextChoices):
"""What happened to an event, as a message's type."""
PUBLISHED = 'event.published', 'Published'
CHANGED = 'event.changed', 'Changed'
CANCELLED = 'event.cancelled', 'Cancelled'
# Chapter 53: the Send test button's message. It is
# about no event, and no endpoint asks for it.
TEST = 'webhook.test', 'Test'
# What an endpoint may choose to hear about.
EVENT_KINDS = [Kind.PUBLISHED, Kind.CHANGED, Kind.CANCELLED]
The form offers only those three. Replace integrations/forms.py:
integrations/forms.py
"""The form for a partner's webhook endpoint (Chapter 52)."""
from django import forms
from . import addresses
from .models import EVENT_KINDS, WebhookEndpoint
class EndpointForm(forms.ModelForm):
"""An address, what it is for, and what it hears about."""
kinds = forms.MultipleChoiceField(
label='Send',
choices=[(kind.value, kind.label)
for kind in EVENT_KINDS],
widget=forms.CheckboxSelectMultiple,
initial=EVENT_KINDS)
class Meta:
model = WebhookEndpoint
fields = ['url', 'description', 'kinds']
labels = {'url': 'Address',
'description': 'Partner'}
help_texts = {
'url': 'https:// only; it must lead to a public '
'address.',
}
def clean_url(self):
"""Refuse an address Otahque may not call."""
url = self.cleaned_data['url']
addresses.check(url)
return url
In integrations/tests/helpers.py, the import becomes
integrations/tests/helpers.py
from integrations.models import EVENT_KINDS, WebhookEndpoint
and the library’s endpoint wants the three event kinds:
A new choice on kind is a change Django records in a migration.
PowerShell:
Windows PowerShell
uv run python manage.py makemigrations integrations `
-n test_message
uv run python manage.py migrate
macOS, Linux, or WSL:
Git Bash, macOS, or Linux
uv run python manage.py makemigrations integrations \
-n test_message
uv run python manage.py migrate
Output
Migrations for 'integrations':
integrations\migrations\0003_test_message.py
~ Alter field kind on webhookdelivery
Operations to perform:
Apply all migrations: account, accounts, admin, api, audit,
auth, contenttypes, django_tasks_database, events,
integrations, mfa, registrations, sessions, socialaccount
Running migrations:
Applying integrations.0003_test_message... OK
Now the sending, in a new module, integrations/trial.py:
integrations/trial.py
"""Send test: one message to an endpoint, now (Chapter 53).
The Webhooks page's Send test button calls send() from an
async view. The slow part is waiting for the partner, up
to 15 seconds; an async view waits without holding a
thread. The message is signed like any other, but it is
sent once, never retried, and never counts toward the
endpoint's failures in a row.
"""
import json
import time
import httpx
from asgiref.sync import sync_to_async
from django.core.exceptions import ValidationError
from django.utils import timezone
from . import addresses, signing
from .models import Kind, WebhookDelivery
from .tasks import TIMEOUT
# Tests put an httpx.MockTransport here instead of the
# network.
transport = None
Status = WebhookDelivery.Status
def message():
"""Return a test message's body, about no event."""
return json.dumps({
'type': Kind.TEST,
'timestamp': timezone.now().isoformat(),
'data': {'message': 'A test from Otahque.'},
}, separators=(',', ':'))
async def send(endpoint):
"""Send endpoint one signed test message; save its row.
Return the delivery, Sent or Failed, with two extras
for the page: seconds, how long it took, and reply, the
start of the partner's answer. The row is saved only
once the answer is in, so a request cancelled on the
way leaves no row behind.
"""
delivery = WebhookDelivery(endpoint=endpoint,
kind=Kind.TEST,
body=message(), attempts=1,
status=Status.FAILED)
delivery.reply = ''
started = time.monotonic()
try:
answer = await post(endpoint, delivery)
except ValidationError as error:
delivery.last_error = error.messages[0][:200]
except httpx.HTTPError as error:
delivery.last_error = (
f'{type(error).__name__}: {error}')[:200]
else:
delivery.last_code = answer.status_code
delivery.reply = answer.text[:200]
if answer.is_success:
delivery.status = Status.SENT
delivery.sent_at = timezone.now()
delivery.seconds = time.monotonic() - started
await delivery.asave()
return delivery
async def post(endpoint, delivery):
"""Send the message with the rules of Chapter 52.
The address is checked in a thread: resolving a name
blocks, and it reads no database, so it need not wait
for Django's one sync thread (thread_sensitive=False).
"""
check = sync_to_async(addresses.check,
thread_sensitive=False)
target = await check(endpoint.url)
stamp = int(timezone.now().timestamp())
sent = signing.headers(endpoint, delivery, stamp)
async with httpx.AsyncClient(
timeout=TIMEOUT, transport=transport,
follow_redirects=False) as client:
return await client.post(
target.url, content=delivery.body,
headers={**sent, 'host': target.netloc},
extensions={'sni_hostname': target.host})
Three choices are worth reading twice. The row is built first, because signing needs its message_id, but saved with asave() only once the answer is in, so a cancelled request leaves no Queued row. The address check runs in a thread with thread_sensitive=False: resolving a name blocks, but it touches no database, so it need not queue for the request’s one sync thread. And async with httpx.AsyncClient() closes the connection however the block ends, cancellation included. A client per request costs a little, which Step 11 measures; Django does not answer ASGI’s lifespan events, as uvicorn said in Step 4, so it has no hook that runs when the server stops, and no clean place to close a client shared across requests. httpx itself stays at 0.28.1: Chapter 51 said it would look at 0.29.0 again here, and 0.29.0 still has no patch release, so the book waits for 0.29.1 or Chapter 62 (N53.8).
Terminal
uv run python manage.py test integrations.tests.test_trial
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Step 8: The Send test view
The tests for the page, in integrations/tests/test_send_test.py:
integrations/tests/test_send_test.py
"""The Send test button, an async view (Chapter 53)."""
from unittest import mock
import httpx
from asgiref.sync import iscoroutinefunction
from django.test import TestCase
from django.urls import reverse
from audit.models import AuditEvent
from config.helpers import in_group
from integrations import trial, views
from integrations.tests.helpers import endpoint, resolving_to
async def accepted(request):
"""Play a partner that accepts every message."""
return httpx.Response(204)
class SendTestTests(TestCase):
"""Who may press it, and what the page shows."""
@classmethod
def setUpTestData(cls):
cls.ann = in_group('ann@example.org', 'Administrators')
cls.sam = in_group('sam@example.org', 'Organizers')
cls.hook = endpoint()
def setUp(self):
self.url = reverse('integrations:test',
args=[self.hook.pk])
patch = mock.patch.object(
trial, 'transport', httpx.MockTransport(accepted))
patch.start()
self.addCleanup(patch.stop)
def test_the_view_stays_async(self):
self.assertTrue(iscoroutinefunction(views.send_test))
async def test_an_organizer_gets_403_recorded(self):
await self.async_client.aforce_login(self.sam)
page = await self.async_client.post(self.url)
self.assertEqual(page.status_code, 403)
self.assertTrue(await AuditEvent.objects.filter(
action='manage_webhooks', outcome='refused',
actor=self.sam).aexists())
async def test_sent_without_the_password_again(self):
await self.async_client.aforce_login(self.ann)
with resolving_to('93.184.215.14'):
page = await self.async_client.post(self.url)
self.assertContains(page, 'Test message')
self.assertContains(page, '204')
self.assertContains(page, '<span class="badge '
'badge-info badge-sm">Test</span>',
html=True)
tested = await AuditEvent.objects.aget(
action='manage_webhooks', outcome='allowed')
self.assertEqual(tested.detail,
{'did': 'tested', 'status': 'sent'})
async def test_htmx_gets_the_card_alone(self):
await self.async_client.aforce_login(self.ann)
with resolving_to('93.184.215.14'):
page = await self.async_client.post(
self.url, headers={'HX-Request': 'true'})
html = page.content.decode()
self.assertTrue(html.strip().startswith(
'<div id="test-result"'))
self.assertNotIn('<html', html)
self.assertIn('hx-swap-oob="true"', html)
self.assertIn('webhook.test', html)
async def test_get_is_not_allowed(self):
await self.async_client.aforce_login(self.ann)
page = await self.async_client.get(self.url)
self.assertEqual(page.status_code, 405)
self.async_client is the async test client: it runs the request through the middleware’s async paths, as an ASGI server would.
Terminal
uv run python manage.py test integrations.tests.test_send_test
Output
Found 5 test(s).
Creating test database for alias 'default'...
ERROR: test_an_organizer_gets_403_recorded
django.urls.exceptions.NoReverseMatch: Reverse for 'test' not
found. 'test' is not a valid view function or pattern
name.
ERROR: test_get_is_not_allowed
django.urls.exceptions.NoReverseMatch: Reverse for 'test' not
found. 'test' is not a valid view function or pattern
name.
ERROR: test_htmx_gets_the_card_alone
django.urls.exceptions.NoReverseMatch: Reverse for 'test' not
found. 'test' is not a valid view function or pattern
name.
... (2 more like these)
Ran 5 tests in ...s
FAILED (errors=5)
webhooks_access wraps every view in a sync function, so on an async view it would hand Django a coroutine where it expects a response. Give it an async branch. In integrations/views.py, the imports become:
integrations/views.py
from allauth.account.decorators import (
reauthentication_required,
)
from asgiref.sync import iscoroutinefunction, sync_to_async
from django.contrib import messages
from django.shortcuts import (
aget_object_or_404, get_object_or_404, redirect, render,
)
from django.views.decorators.cache import never_cache
from django.views.decorators.http import (
require_http_methods, require_POST,
)
from audit.models import AuditEvent, record
from events.views import deny
from . import trial
from .forms import EndpointForm
from .models import WebhookEndpoint
and the decorator:
integrations/views.py
def webhooks_access(view):
"""Allow holders of manage_webhooks; refuse the rest.
A refusal is 403 and recorded, as on Chapter 30's pages.
Chapter 53: an async view gets an async check, so it
stays async; a sync wrapper would hand Django a
coroutine where it expects a response.
"""
if iscoroutinefunction(view):
@wraps(view)
async def async_wrapper(request, *args, **kwargs):
# Keep the member auser() read, so sync code that
# reads request.user later, such as Django's 403
# page, needs no query of its own.
request.user = user = await request.auser()
if not await user.ahas_perm(
'integrations.manage_webhooks'):
await sync_to_async(deny)(
request, Action.MANAGE_WEBHOOKS)
return await view(request, *args, **kwargs)
return async_wrapper
@wraps(view)
def wrapper(request, *args, **kwargs):
if not request.user.has_perm(
'integrations.manage_webhooks'):
deny(request, Action.MANAGE_WEBHOOKS)
return view(request, *args, **kwargs)
return wrapper
user.ahas_perm() is the async form of has_perm(); the refusal, which writes an audit row, runs in a thread. The member that auser() read is kept as request.user, for the reason the Common Error below explains. Then, at the end of the file:
integrations/views.py
@require_POST
@webhooks_access
async def send_test(request, endpoint_id):
"""Send the endpoint a test message now; show the answer.
Async (Chapter 53): the wait for the partner holds no
thread. No password is asked again: it changes nothing
and shows no secret. htmx gets the result card alone.
"""
found = await aget_object_or_404(WebhookEndpoint,
pk=endpoint_id)
delivery = await trial.send(found)
user = await request.auser()
await sync_to_async(record)(
user, Action.MANAGE_WEBHOOKS, found, did='tested',
status=delivery.status)
page = 'integrations/endpoint.html'
if request.htmx:
page += '#test-result'
# render() runs in a thread: the page's header reads
# request.user, a query async code may not make.
return await sync_to_async(render)(request, page, {
'endpoint': found, 'tested': delivery,
'deliveries': found.deliveries.all()[:50],
'swapped': bool(request.htmx),
})
Send test asks for no password again, unlike Rotate and Turn off: it changes nothing and shows no secret (N53.4), and allauth’s reauthentication_required is sync-only, so it would turn the view back into a sync one. render() runs in a thread, because the page’s header reads request.user. In integrations/urls.py, add its address after switch:
On the endpoint’s page, integrations/templates/integrations/endpoint.html, add the button and the card for its answer above the action bar:
integrations/templates/integrations/endpoint.html
{# Chapter 53: one signed message, sent now. With htmx #}
{# the card below is replaced; without, the page is. #}
{% url 'integrations:test' endpoint.pk as test_url %}
<form method="post" action="{{ test_url }}"
class="test-form" hx-post="{{ test_url }}"
hx-target="#test-result" hx-swap="outerHTML"
hx-disabled-elt="find button">
{% csrf_token %}
<button type="submit" class="btn btn-primary">
{% include "includes/spinner.html" %}
Send test</button>
<span class="text-sm">A signed webhook.test message,
sent once; partners can ignore it.</span>
</form>
{% partialdef test-result inline %}
<div id="test-result" aria-live="polite">
{% if tested %}
<section class="token-card test-card
test-{{ tested.status }}"
aria-labelledby="test-heading">
<h2 id="test-heading">Test message
{% with status=tested.status %}
{% include "includes/status_badge.html" %}
{% endwith %}</h2>
<dl class="test-facts">
<dt>Answer</dt>
<dd>{{ tested.last_code|default:"none" }}</dd>
<dt>Time</dt>
<dd>{{ tested.seconds|floatformat:2 }} s</dd>
{% if tested.last_error %}
<dt>Problem</dt>
<dd>{{ tested.last_error }}</dd>
{% endif %}
{% if tested.reply %}
<dt>Reply</dt>
<dd><code>{{ tested.reply|truncatechars:80 }}</code>
</dd>
{% endif %}
</dl>
</section>
{% endif %}
</div>
{% if swapped %}{% partial delivery-log %}{% endif %}
{% endpartialdef %}
With htmx, the button replaces only the card; without JavaScript, the form posts and the whole page comes back with the card filled in. {% partialdef %}, from Chapter 45, names the card so the view can render it alone. The log below should show the new message too, so make it a partial that the same answer replaces out of band. Its opening tag becomes:
integrations/templates/integrations/endpoint.html
{# Chapter 53: after Send test, htmx also replaces the #}
{# log, out of band, so the new message shows at once. #}
{% partialdef delivery-log inline %}
<table id="delivery-log" class="stack-table"
{% if swapped %}hx-swap-oob="true"{% endif %}>
uv run python manage.py test integrations.tests.test_send_test
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Common Error: database table is locked, or a connection left ope
Without request.user = user in the decorator, the refusal test fails on SQLite with “database table is locked”, and on PostgreSQL the test database cannot be dropped because “1 other session” is using it. When an async view raises PermissionDenied, Django builds the 403 page in a thread outside the request’s, and the page’s header reads request.user. Unread until then, it is fetched from the database on a connection of that thread’s own: one that cannot see a TestCase’s uncommitted rows, and that nobody closes. Keeping the member auser() already read means the page needs no query at all.
The library’s receiver from Chapter 52 must recognize the new type too: its message carries no event, so data['id'] would fail and the receiver would answer nothing. A test for it, in integrations/tests/test_receiver.py, before test_an_older_version_is_ignored:
uv run python manage.py test integrations.tests.test_receiver
Output
Found 6 test(s).
Creating test database for alias 'default'...
ERROR: test_a_test_message_is_received
KeyError: 'id'
Ran 6 tests in ...s
FAILED (errors=1)
In examples/receiver.py, after the id is recorded:
examples/receiver.py
self.seen.add(message_id)
# Chapter 53: Send test's message is about no event.
if message['type'] == 'webhook.test':
return 200, 'webhook.test: received'
data = message['data']
Terminal
uv run python manage.py test integrations.tests.test_receiver
Output
Found 6 test(s).
Creating test database for alias 'default'...
...
Ran 6 tests in ...s
OK
Partners write their own receivers, so tell them too. In docs/api/contract.md, the table of types ends:
docs/api/contract.md
| `event.cancelled` | A published event is cancelled |
| `webhook.test` | An administrator presses Send test |
A `webhook.test` message (Chapter 53) is sent once, never
retried, and its `data` holds only `message`; answer it
2xx and change nothing.
Step 9: Try Send test
The card needs a coloured edge and the status in words; and while htmx waits, screen readers should know the answer is coming. In static/otahque/source.css, before .form-actions:
static/otahque/source.css
/* Chapter 53: Send test, and the card with its answer:
a coloured edge and the status in words. */
.test-form {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.75rem;
margin-bottom: 1rem;
}
.test-card {
margin-bottom: 1.5rem;
border-left: 6px solid var(--color-base-300);
}
.test-card.test-sent {
border-left-color: var(--color-success);
}
.test-card.test-failed {
border-left-color: var(--color-error);
}
.test-card h2 {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.test-facts {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
gap: 0.25rem 1rem;
}
.test-facts dt {
font-weight: 600;
}
.test-facts dd {
overflow-wrap: anywhere;
}
At the end of static/otahque/site.js, for every htmx request on every page:
static/otahque/site.js
// Chapter 53: while htmx waits, mark the part it will
// replace as busy, so screen readers wait for the answer
// rather than read the old content.
document.addEventListener('htmx:beforeRequest', (event) => {
event.detail.target.setAttribute('aria-busy', 'true');
});
document.addEventListener('htmx:afterRequest', (event) => {
event.detail.target.removeAttribute('aria-busy');
});
Terminal
npm run build
Now press it for real. In one terminal, start the receiver with the library’s secret from Chapter 52, as in Chapter 52’s Step 12; in another, runserver. Sign in as an administrator, open Webhooks, then Library, and press Send test. The spinner shows on the button, which is disabled until the answer arrives; then the card says Sent with the answer 200 and the time it took, the receiver prints
Folder structure
Listening on http://127.0.0.1:8001/
webhook.test: received
Listening on http://127.0.0.1:8001/
webhook.test: received
and the log’s first row is the webhook.test message with a Test badge, without the page reloading. Stop the receiver and press it again: the card turns red and says Failed, with ConnectError and the time it took to give up. Figure 53.4 shows both.
Figure 53.4 — Send test on a phone, and a failure on a wide screen.
Stop the server and the receiver with Ctrl+C.
Step 10: The attendee download under ASGI
Since Step 3 Otahque runs on ASGI, so Chapter 41’s download now arrives whole, after Django has read every row. The tests show it if they read the download as an ASGI server does, with async for, and treat Django’s warning as a failure. In registrations/tests/test_download.py, the top of the file becomes:
registrations/tests/test_download.py
"""The attendee download: who, what, and how (Chapter 41)."""
import warnings
from unittest import mock
from asgiref.sync import sync_to_async
from django.test import TestCase
from django.utils import timezone
from accounts.models import Profile
from audit.models import AuditEvent
from config.helpers import answers, in_group
from events.models import Event
from events.tests.test_methods import SIGNED_OUT_FIRST
from registrations import table
from registrations.models import RegistrationQuestion as Question
from .test_registrations import soon, url, verified
Action = AuditEvent.Action
async def text_of(response):
"""Return a streamed download as one string.
Chapter 53: read the way an ASGI server reads it, with
async for. A warning, such as the one Django gives when
it must read a sync iterator whole first, fails the test.
"""
with warnings.catch_warnings():
warnings.simplefilter('error')
parts = [part async for part in response]
return b''.join(parts).decode()
def with_company(email):
"""Create a member whose profile names a company."""
member = verified(email)
profile = Profile.of(member)
profile.company = 'Library'
profile.save()
return member
in setUpTestData() keep the question, for a test below:
registrations/tests/test_download.py
cls.level = level = Question.objects.create(
and the rest of DownloadTests, from setUp(), becomes:
registrations/tests/test_download.py
def setUp(self):
self.async_client.force_login(self.sam)
def download(self):
"""Download the event's CSV as Sam, as ASGI would."""
return self.async_client.get(
url('download', self.event.pk))
async def test_a_named_csv_file(self):
response = await self.download()
self.assertEqual(response['Content-Type'],
'text/csv; charset=utf-8')
name = f'attendees-{self.event.pk}.csv'
self.assertEqual(response['Content-Disposition'],
f'attachment; filename="{name}"')
async def test_the_columns_and_the_bom(self):
text = await text_of(await self.download())
header = text.splitlines()[0]
self.assertTrue(header.startswith('\ufeffName,Email,'))
self.assertTrue(header.endswith(',Company,Python level'))
async def test_typed_text_cannot_run_as_a_formula(self):
text = await text_of(await self.download())
row = text.splitlines()[1]
quoted = '"\'=HYPERLINK(""http://x.example"")"'
self.assertTrue(row.startswith(quoted))
self.assertIn(",'-1 beginner", row)
self.assertIn('Søren & Co', row)
async def test_the_phone_is_spaced_and_not_guarded(self):
text = await text_of(await self.download())
row = text.splitlines()[1]
self.assertIn(',+44 7700 900123,', row)
async def test_each_download_is_recorded(self):
await text_of(await self.download())
record = await AuditEvent.objects.select_related(
'actor').aget(action=Action.DOWNLOAD_ATTENDEES)
self.assertEqual(record.actor, self.sam)
self.assertEqual(record.detail, {'rows': 1})
async def test_head_records_nothing(self):
await self.async_client.head(
url('download', self.event.pk))
self.assertFalse(await AuditEvent.objects.filter(
action=Action.DOWNLOAD_ATTENDEES).aexists())
async def test_the_administrator_may_download(self):
soni = await sync_to_async(in_group)(
'soni@example.org', 'Administrators')
await self.async_client.aforce_login(soni)
response = await self.download()
self.assertEqual(response.status_code, 200)
async def test_a_client_that_leaves_stops_the_rows(self):
await Event.objects.filter(pk=self.event.pk).aupdate(
capacity=10)
for n in range(4):
member = await sync_to_async(with_company)(
f'guest{n}@example.org')
await sync_to_async(self.event.register)(
member, timezone.now(),
answers={self.level.key: 'new'})
response = await self.download()
with mock.patch('registrations.table.row',
wraps=table.row) as made:
parts = aiter(response)
for _ in range(3):
await anext(parts)
await parts.aclose()
self.assertEqual(made.call_count, 1)
The last test reads the byte order mark, the header, and one row, then stops, as a browser does when someone cancels a download; only one row should have been made.
Terminal
uv run python manage.py test registrations.tests.test_download
Output
Found 11 test(s).
Creating test database for alias 'default'...
ERROR: test_a_client_that_leaves_stops_the_rows
AttributeError: module 'registrations.table' has no attribute
'row'
ERROR: test_each_download_is_recorded
Warning: StreamingHttpResponse must consume synchronous
iterators in order to serve them asynchronously. Use an
asynchronous iterator instead.
ERROR: test_the_columns_and_the_bom
Warning: StreamingHttpResponse must consume synchronous
iterators in order to serve them asynchronously. Use an
asynchronous iterator instead.
... (2 more like these)
Ran 11 tests in ...s
FAILED (errors=5)
There is the warning. In registrations/table.py, the imports become:
registrations/table.py
import csv
from zoneinfo import ZoneInfo
from asgiref.sync import sync_to_async
from django.utils import timezone
and csv_lines(), at the end of the file, becomes an async generator, with each row made by a function of its own:
registrations/table.py
async def csv_lines(event, places):
"""Yield the download, line by line, starting with a BOM.
The byte order mark tells Excel the file is UTF-8, so
names such as Søren arrive intact. Chapter 53: an async
generator, so an ASGI server streams it as it is made.
The columns are read first, in a thread; async for then
reads the places, each with its member and profile
(with_people()), so a row needs no further query.
"""
facts, questions = await sync_to_async(columns)(event)
zone = ZoneInfo(event.timezone)
writer = csv.writer(Echo())
yield ''
yield writer.writerow(
[guarded(cell)
for cell in headings(event, facts, questions)])
async for place in places:
yield writer.writerow(row(place, zone, facts,
questions))
def row(place, zone, facts, questions):
"""Return one place's cells, guarded where typed."""
member = place.member
registered = timezone.localtime(place.registered_at, zone)
fact_values, answers = extra_cells(place, facts,
questions)
return ([guarded(member.display_name),
guarded(member.email),
phone_cell(member),
f'{registered:%Y-%m-%d %H:%M}']
+ [guarded(value) for value in fact_values]
+ [guarded(value) for value in answers])
async for over a queryset fetches its rows in chunks without blocking the loop. Each row needs no further query, because with_people() already brought each place’s member and profile, so nothing in the loop calls the ORM the sync way. In registrations/views.py, add the import:
registrations/views.py
import logging
from asgiref.sync import sync_to_async
from django.contrib import messages
and make the download’s get() async:
registrations/views.py
async def get(self, request, event_id):
"""Record the download, then stream the file.
Chapter 53: async, so that under ASGI the file goes
out row by row instead of being built whole first.
The checks and the record are sync code, so they run
in a thread.
"""
event = await sync_to_async(attendees_of)(
request, event_id, Action.DOWNLOAD_ATTENDEES)
places = event.registrations.active().with_people()
if request.method == 'GET':
user = await request.auser()
await sync_to_async(record)(
user, Action.DOWNLOAD_ATTENDEES, event,
rows=await places.acount())
A class-based view is async when its handlers are: Django checks that get() is a coroutine function and runs the view accordingly. The access check and the audit record are sync code that queries and writes, so they run in the request’s thread; acount() counts the rows.
Terminal
uv run python manage.py test registrations.tests.test_download
Output
Found 11 test(s).
Creating test database for alias 'default'...
...
Ran 11 tests in ...s
OK
Common Error: a lazy query inside the async generato
Without with_people(), reading place.member in the loop would make one query per row, the sync way, inside the async generator. Django refuses it with SynchronousOnlyOperation, and because the response has already started, the browser receives a file cut off after the header. Fetch everything a row needs before the loop, with select_related() or prefetch_related(), and keep the loop free of queries.
Step 11: Measure
Does an async view serve slow calls faster? Measure it, on a project small enough to read. Create examples/waiting.py, a whole Django project in one file:
examples/waiting.py
"""Waiting for a slow partner, sync and async (Chapter 53).
Not part of Otahque: a whole Django project in one file,
with two views that each call a partner who takes two
seconds to answer. Run each command in its own terminal:
uv run python examples/waiting.py partner
uv run python examples/waiting.py serve
uv run python examples/waiting.py measure sync 60
partner plays the slow partner on port 8009. serve runs
Daphne's runserver on port 8002. measure sends N requests
at once to the sync or the async view, and prints how long
they took in all, and the most threads the server used.
"""
import asyncio
import sys
import threading
import time
import httpx
from django.conf import settings
from django.core.asgi import get_asgi_application
from django.http import HttpResponse
from django.urls import path
PARTNER = 'http://127.0.0.1:8009/'
SERVER = 'http://127.0.0.1:8002/'
settings.configure(
DEBUG=False,
ALLOWED_HOSTS=['127.0.0.1'],
ROOT_URLCONF=__name__,
SECRET_KEY='only-for-this-example',
INSTALLED_APPS=['daphne'],
ASGI_APPLICATION=f'{__name__}.application',
)
def answered(status):
"""Return the partner's status and the threads alive."""
threads = threading.active_count()
return HttpResponse(f'{status} {threads}\n')
def wait_sync(request):
"""Call the partner with httpx.Client: a thread waits."""
with httpx.Client(timeout=15) as client:
answer = client.get(PARTNER)
return answered(answer.status_code)
async def wait_async(request):
"""Call the partner with httpx.AsyncClient, as Send test."""
async with httpx.AsyncClient(timeout=15) as client:
answer = await client.get(PARTNER)
return answered(answer.status_code)
urlpatterns = [path('sync/', wait_sync),
path('async/', wait_async)]
application = get_asgi_application()
async def partner():
"""Answer every request on port 8009 after 2 seconds."""
async def answer(reader, writer):
await reader.readuntil(b'\r\n\r\n')
await asyncio.sleep(2)
writer.write(b'HTTP/1.1 200 OK\r\n'
b'content-length: 3\r\n'
b'connection: close\r\n\r\nok\n')
await writer.drain()
writer.close()
server = await asyncio.start_server(
answer, '127.0.0.1', 8009, backlog=1000)
async with server:
await server.serve_forever()
async def measure(kind, count):
"""Send count requests at once to one view; report."""
limits = httpx.Limits(max_connections=None)
async with httpx.AsyncClient(timeout=60,
limits=limits) as client:
started = time.perf_counter()
answers = await asyncio.gather(*[
client.get(f'{SERVER}{kind}/')
for _ in range(count)])
took = time.perf_counter() - started
threads = max(int(a.text.split()[1]) for a in answers)
print(f'{count} {kind} calls: {took:.1f} s, '
f'at most {threads} threads')
if __name__ == '__main__':
command = sys.argv[1]
if command == 'partner':
asyncio.run(partner())
elif command == 'serve':
from django.core.management import (
execute_from_command_line,
)
execute_from_command_line(
[sys.argv[0], 'runserver', '8002', '--noreload'])
else:
asyncio.run(measure(sys.argv[2], int(sys.argv[3])))
Each view answers with the partner’s status and how many threads the process has. Run the partner in one terminal:
Terminal
uv run python examples/waiting.py partner
the server in a second:
Terminal
uv run python examples/waiting.py serve
and, in a third, three calls at once, then sixty, to the sync view:
Terminal
uv run python examples/waiting.py measure sync 3
uv run python examples/waiting.py measure sync 60
Stop the server and start it again, so no threads carry over, then measure the async view:
Terminal
uv run python examples/waiting.py measure async 3
uv run python examples/waiting.py measure async 60
To repeat both under uvicorn, run uv run uvicorn examples.waiting:application --port 8002 in the second terminal instead. Table 53.1 shows one run of all eight; your numbers will differ with your computer.
Table 53.1 — A partner that takes 2 seconds: one run on one Windows 11 laptop, 8 logical processors, Python 3.14.9
Server
View
Calls at once
Time for all
Most threads
Daphne's runserver
sync
3
2.2 s
5
Daphne's runserver
sync
60
2.4 s
62
Daphne's runserver
async
3
2.3 s
5
Daphne's runserver
async
60
3.2 s
62
uvicorn
sync
3
2.2 s
5
uvicorn
sync
60
2.4 s
62
uvicorn
async
3
2.3 s
5
uvicorn
async
60
3.2 s
62
Read the numbers before the conclusion. Three calls to a partner that takes 2 seconds took about 2 seconds whichever view and server answered them: neither kind of view made them wait in line. Sixty calls took a little longer, and the async view was slower, not faster, because it makes a new client, with its connection setup, for every request. And both views used about one thread per request in flight: Django runs its own sync signal handlers in a thread for each request, as the Under the Hood box explained. The difference is what those threads do. The sync view’s threads are blocked in the network call; the async view’s sit idle while the event loop waits, and the async view can be cancelled when the client leaves, which a blocked thread cannot.
So the book makes no speed claim (N53.7). Async earns its place in Otahque where it changes what is possible: a wait that is cancelled when nobody is watching, a download that streams on an ASGI server, and, in Chapter 54, connections that stay open for minutes. Chapter 66 measures the whole application under load. Stop the partner and the server with Ctrl+C.
Step 12: The checks, and the commit
Terminal
uv run python check.py
Output
== python manage.py check
System check identified no issues (0 silenced).
== python manage.py makemigrations --check --dry-run
No changes detected
== python manage.py test --parallel
Found 789 test(s).
System check identified no issues (0 silenced).
Ran 789 tests in ...s
OK
== all checks passed
Terminal
git add .
git status --short
git commit -m "Serve Otahque over ASGI; send a test webhook"
Output
M accounts/middleware.py
M accounts/timezones.py
M audit/middleware.py
M config/middleware.py
M config/settings.py
A config/tests/test_async.py
M docs/api/contract.md
A examples/boundary.py
M examples/receiver.py
A examples/waiting.py
M integrations/forms.py
A integrations/migrations/0003_test_message.py
M integrations/models.py
M integrations/templates/integrations/endpoint.html
M integrations/tests/helpers.py
M integrations/tests/test_receiver.py
A integrations/tests/test_send_test.py
A integrations/tests/test_trial.py
A integrations/trial.py
M integrations/urls.py
M integrations/views.py
M pyproject.toml
M registrations/table.py
M registrations/tests/test_download.py
M registrations/views.py
M static/otahque/site.css
M static/otahque/site.js
M static/otahque/source.css
M uv.lock
[main 1a2b3c4] Serve Otahque over ASGI; send a test webhook
29 files changed, 1382 insertions(+), 69 deletions(-)
create mode 100644 config/tests/test_async.py
create mode 100644 examples/boundary.py
create mode 100644 examples/waiting.py
create mode 100644
integrations/migrations/0003_test_message.py
create mode 100644 integrations/tests/test_send_test.py
create mode 100644 integrations/tests/test_trial.py
create mode 100644 integrations/trial.py
If something goes wrong
Table 53.2 — Recovery for Chapter 53
What you see
Likely cause
What to do
runserver still says Starting development server
daphne not first in INSTALLED_APPS
Move it to the top; restart
Cannot find ASGI_APPLICATION setting
The setting is missing
Add ASGI_APPLICATION = 'config.asgi.application'
Pages unstyled, site.css 404
Served by uvicorn, which serves no static files
Use runserver while developing
SynchronousOnlyOperation
A sync query in async code
Use aget(), acount(), async for, or sync_to_async()
It returned an unawaited coroutine instead
A sync decorator around an async view
Give the decorator an async branch, as webhooks_access
StreamingHttpResponse must consume synchronous iterators
A sync generator under ASGI
Make it an async generator, and the view async
database table is locked, in an async test
The 403 page reads request.user in another thread
Set request.user from auser() before refusing
Send test says ConnectError
The receiver is not running
Start examples/receiver.py with the endpoint's secret
Work through Table 53.3 from the folder that holds manage.py, with Otahque on PostgreSQL.
Table 53.3 — Verification checklist for Chapter 53
Check
Command or action
Expected result
Starting point
test --parallel
Found 772 test(s); OK
Security release
uv add django==6.1.3; test --parallel
6.1.2 replaced by 6.1.3; 772 tests OK
Daphne
uv add daphne==4.2.3; runserver
Starting ASGI/Daphne version 4.2.3; page and site.css 200
Another server
uvicorn config.asgi:application
Page 200; site.css 404, unstyled
The boundary
examples/boundary.py
count() refused; acount() and sync_to_async work
Middleware
test config.tests.test_async
Three classes listed first; then 5 tests OK
A test message
test ...test_trial
ImportError first; then 5 tests OK
The view
test ...test_send_test; test_receiver
Errors first; then 5 and 6 tests OK
Send test for real
runserver, receiver, the endpoint's page
Sent and 200; Failed with the receiver stopped; Test badge in the log; 390 and 1280 px
The download
test ...test_download
The warning first; then 11 tests OK
Measure
examples/waiting.py, sync and async, two servers
Eight timings with the machine
All checks
uv run python check.py
== all checks passed; Ran 789 tests
Commit
git log --oneline -1
Serve Otahque over ASGI; send a test webhook
Not verified
A real partner over TLS; a production ASGI server; a browser closing a download mid-file; macOS and Linux shells
Covered by tests with stand-ins, or later chapters
The commands were checked in Windows PowerShell 5.1 and Git Bash, from a copy of the Chapter 52 checkpoint with a reader’s data, against PostgreSQL 18; commands that write files ran once, and each server was started in both shells, asked for the events page and the stylesheet, and stopped. Step 9 ran for real: Daphne’s runserver, examples/receiver.py started with the library endpoint’s secret, and Microsoft Edge, signed in as an administrator, pressing Send test at 1280 pixels (Sent, 200, the log updated without a reload), again with the receiver stopped (Failed, ConnectError), and once at 390 pixels, with no sideways scroll and every control named. Step 11’s eight timings were taken on fresh servers, one Windows 11 laptop with 8 logical processors running the partner, the server, and the client together.
Que. 1 Under ASGI, what does Django do with a sync view, and with a sync-only middleware class?
Flip to check your answerFold answer back
Answer. It runs the sync view in a thread, so it cannot block the event loop. For a sync-only middleware class it switches to a thread before the class and back after it, on every request; an async-capable class is awaited directly.
Que. 2 Why does Event.objects.count() inside a coroutine raise SynchronousOnlyOperation, and what are the two fixes?
Flip to check your answerFold answer back
Answer. A sync query would block the event loop and every coroutine on it, so Django refuses it. Use the async method, acount(), or hand the sync call to a thread with sync_to_async().
Que. 3 Why did Chapter 41’s download stop streaming when Otahque moved to Daphne?
Flip to check your answerFold answer back
Answer. An ASGI server reads a streaming response with async for. A sync generator cannot be read that way, so Django reads it to the end first, holds the whole file, and warns. An async generator streams again.
Que. 4 Why is Send test’s row saved only after the partner answers?
Flip to check your answerFold answer back
Answer. Its status should be Sent or Failed, never Queued. If the request is cancelled while waiting, because the browser went away, nothing is saved and no Queued row is left for anyone to wonder about.
Que. 5 What did Step 11’s measurement show, and what does the book conclude?
Flip to check your answerFold answer back
Answer. Three calls to a 2-second partner took about 2 seconds with either view; sixty took a little longer, and the async view, which makes a client per request, was slower. Both used about a thread per request in flight. So no speed claim: async is used where it changes what is possible, such as cancelling a wait, streaming under ASGI, and holding connections open.
Mini-Challenge
Chapter 52’s rules say a redirect is a failure and is never followed; Send test must keep that rule. Write a test, in integrations/tests/test_no_redirect.py, in which the partner answers 302 with a location inside the network, and check that only one request was made and the test message failed with the answer 302.
Hint:trial.transport takes an httpx.MockTransport, and its handler may be async; endpoint() saves the library’s endpoint, from a sync context.
Model answer:
integrations/tests/test_no_redirect.py
"""Send test follows no redirect (Chapter 53 challenge)."""
from unittest import mock
import httpx
from asgiref.sync import sync_to_async
from django.test import TestCase
from integrations import trial
from integrations.tests.helpers import endpoint, resolving_to
class NoRedirectTests(TestCase):
"""A 302 is the answer, never a second request."""
async def test_a_redirect_is_a_failure(self):
hook = await sync_to_async(endpoint)()
seen = []
async def handle(request):
seen.append(request.url)
return httpx.Response(
302, headers={'location': 'http://10.0.0.5/'})
transport = httpx.MockTransport(handle)
with (mock.patch.object(trial, 'transport', transport),
resolving_to('93.184.215.14')):
delivery = await trial.send(hook)
self.assertEqual(len(seen), 1)
self.assertEqual(delivery.status, 'failed')
self.assertEqual(delivery.last_code, 302)
Terminal
uv run python manage.py test integrations.tests.test_no_redirect
Output
Found 1 test(s).
Creating test database for alias 'default'...
...
Ran 1 test in ...s
OK
follow_redirects=False is the default in httpx, and trial.py says it anyway, so a later reader does not have to know. The model answer was run and then removed; the chapter’s checkpoint does not include it.
What We Learned
Concurrency is taking turns while waiting; async code takes turns on one event loop, and every wait must be an await.
WSGI calls a project as a function; ASGI awaits it as a coroutine and can hold connections open. Django runs both kinds of view under both servers, adapting with threads.
Daphne first in INSTALLED_APPS makes runserver an ASGI server; uvicorn serves the same application, without static files.
The ORM is sync: in async code use its a methods or sync_to_async(), and keep transactions in sync functions.
Middleware and decorators must handle both kinds of call, or they push an async view back onto a thread, or break it.
Under ASGI a streaming response needs an async generator, with no queries inside the loop.
Measure before claiming: here async made nothing faster, and Otahque uses it where it changes what is possible.
Key terms
Use Table 53.4 to explain this chapter’s ideas in your own words.
Table 53.4 — Key terms from Chapter 53
Term
Meaning
Concurrency
Several tasks in progress at once, taking turns.
Parallelism
Several tasks running at the same instant on different cores.
Coroutine
A function defined with async def; it pauses at each await.
Event loop
The scheduler that runs coroutines and resumes each when its wait ends.
WSGI
The sync interface between a Python server and an application.
ASGI
Its async successor, which can also hold connections open.
sync_to_async
asgiref's wrapper that runs a sync function in a thread and awaits it.
SynchronousOnlyOperation
Django's refusal of a sync database call from async code.
Async-capable middleware
A class that can be awaited directly, so no thread switch.
Async generator
An async def function that yields, read with async for.
Readiness checkpoint: you are ready for Chapter 54 when uv run python check.py ends with “all checks passed” and 789 tests, runserver says “Starting ASGI/Daphne”, Send test shows Sent for the library’s endpoint with the receiver running, and git log --oneline -1 shows this chapter’s commit.
Git Commit
Your Chapter 53 work was committed once, in Step 12, as “Serve Otahque over ASGI; send a test webhook”: pyproject.toml and uv.lock; the settings; the three middleware classes and the time zone helper; the integrations models, migration, form, views, addresses, trial.py, the endpoint page, and three test modules; the download’s view, table, and tests; the receiver and the contract; the stylesheet, compiled CSS, and site.js; and the two examples. If you kept the Mini-Challenge, commit it on its own:
Terminal
git add integrations/tests/test_no_redirect.py
git commit -m "Check that Send test follows no redirect"
These five questions rehearse the chapter at interview level, from junior to lead. L1 to L3 check what you have just done. L4 and L5 look ahead, to a download that buffers in production and to defending a measurement against a team that wants to “go async”. They are extension questions, not a gate to the next chapter. Each code proof is a run from this chapter’s steps.
L1 (Junior): What does async help a web application with?
What the interviewer is testing: Can you tell waiting from working, and name where async fits?
Flip to check your answerFold answer back
Perfect answer: Async helps with waiting: calls to other servers, long streams, and connections that stay open. A coroutine awaits instead of blocking, so one event loop keeps many waits in progress, and a waiting request can be cancelled when its client leaves. It does not speed up work the processor or the database does, and Django’s ORM is sync, so a page that mostly reads the database gains nothing. In Otahque, Send test waits up to 15 seconds for a partner, so it is async; the events list is not.
Code proof: the test message’s tests, including the cancelled call:
Output
Found 5 test(s).
Creating test database for alias 'default'...
...
Ran 5 tests in ...s
OK
Common mistakes:
Expecting async to make every page faster.
Calling a sync library, such as requests, inside an async view, which blocks the loop.
Follow-up the interviewer might ask:
How would you wait for three partners at once? (asyncio.gather() over three awaits, each with its own timeout.)
L2 (Mid-Level): Predict what an ORM call does inside an async view
What the interviewer is testing: Do you know the sync/async boundary in Django’s ORM, and its fixes?
Flip to check your answerFold answer back
Perfect answer: It raises SynchronousOnlyOperation before the query runs: a sync query in a coroutine would block the event loop, so Django checks for a running loop and refuses. The fix is the async method, such as aget(), acount(), afirst(), or async for, or wrapping a sync function in sync_to_async(), which runs it in the request’s thread. A lazy relation, such as place.member without select_related(), is the same sync query in disguise. And transactions do not work in async mode yet, so a write that needs atomic() belongs in a sync function called through sync_to_async().
count(): SynchronousOnlyOperation
You cannot call this from an async context - use a thread
or sync_to_async.
acount(): 14
sync_to_async(count)(): 14
Common mistakes:
Setting DJANGO_ALLOW_ASYNC_UNSAFE to make the error go away.
Forgetting that a template reading request.user queries too; render such a page in a thread.
Follow-up the interviewer might ask:
Why does sync_to_async() default to thread_sensitive=True? (Sync code that expects one thread, such as a database connection, always gets the request’s same thread.)
L3 (Senior): Defend making two views async, not the whole application
What the interviewer is testing: Can you weigh what async costs against what it gains, view by view?
Flip to check your answerFold answer back
Perfect answer: Each async view that touches the database needs async query methods or sync_to_async(), its decorators and middleware must handle both kinds of call, and its tests need the async client; that cost is paid in every view converted. The gain comes only where the view waits on something other than Django’s own database. Otahque has two such views: Send test, which waits for a partner, and the attendee download, which streams. Everything else stays sync and runs in a thread under ASGI, which is fine. What must be ready for both everywhere is the shared path, middleware above all, because one sync-only class adds two thread switches to every request, sync or async. A test over MIDDLEWARE keeps it so.
Figure 53.6 — Choosing what to make async.
Behind the scenes:
Output
send_test, download async
middleware sync_capable and async_capable
all other views sync, run in a thread under ASGI
Code proof: the middleware test before the three classes were changed, from Step 6:
Output
Found 5 test(s).
Creating test database for alias 'default'...
ERROR: test_the_id_reaches_the_view_and_header
TypeError: 'coroutine' object does not support item
assignment
ERROR: test_the_profile_zone_is_read_with_await
AttributeError: 'WSGIRequest' object has no attribute 'user'.
Did you mean: 'auser'?
FAIL: test_an_async_chain_stays_async [CredentialMiddleware]
AssertionError: False is not true
FAIL: test_an_async_chain_stays_async [RequestIDMiddleware]
AssertionError: False is not true
FAIL: test_an_async_chain_stays_async [TimezoneMiddleware]
AssertionError: False is not true
FAIL: test_every_class_is_async_capable
AssertionError: Lists differ:
['config.middleware.RequestIDMiddleware', [77 chars]are']
!= []
FAIL: test_no_token_is_carried_in
AssertionError: False is not true
Ran 5 tests in ...s
FAILED (failures=5, errors=2)
Common mistakes:
Converting views one by one with no rule for the shared path, so each one still changes threads in middleware.
Adding a decorator that wraps views in a sync function, which silently breaks the async ones.
Follow-up the interviewer might ask:
How would you find which middleware forces a thread switch? (With DEBUG on, Django logs “Asynchronous handler adapted for middleware ...” at debug level on the django.request logger; the test makes it a failure instead.)
L4 (Staff): A CSV export works but uses a gigabyte of memory in production. Diagnose it
What the interviewer is testing: Can you connect a symptom to the server interface?
Flip to check your answerFold answer back
Perfect answer: I would first ask what changed: if the export streamed under WSGI and the service moved to an ASGI server, the response’s iterator is probably sync. An ASGI server reads a streaming response with async for; Django cannot do that with a sync generator, so it reads it into a list first, holds the whole file, then sends it, and logs “StreamingHttpResponse must consume synchronous iterators in order to serve them asynchronously”. The memory grows with the file, and nothing reaches the browser until the end. I would confirm with the warning in the logs, or a test that reads the response with async for and treats warnings as errors. The fix is an async generator over the queryset with async for, every related row fetched beforehand, and an async view, so the file streams again and stops when the client leaves.
Figure 53.7 — Diagnosing a stream that buffers.
Behind the scenes:
Output
WSGI for part in iterator streams
ASGI list(sync iterator) first whole file in memory
ASGI async for part in agen streams
Code proof: the download’s tests before csv_lines() was made async, from Step 10:
Output
Found 11 test(s).
Creating test database for alias 'default'...
ERROR: test_a_client_that_leaves_stops_the_rows
AttributeError: module 'registrations.table' has no attribute
'row'
ERROR: test_each_download_is_recorded
Warning: StreamingHttpResponse must consume synchronous
iterators in order to serve them asynchronously. Use an
asynchronous iterator instead.
ERROR: test_the_columns_and_the_bom
Warning: StreamingHttpResponse must consume synchronous
iterators in order to serve them asynchronously. Use an
asynchronous iterator instead.
... (2 more like these)
Ran 11 tests in ...s
FAILED (errors=5)
Common mistakes:
Raising the server’s memory instead of finding the warning.
Making the generator async but querying lazily inside it, which fails halfway through the file.
Follow-up the interviewer might ask:
What happens to the export when the user cancels the download? (Under ASGI the generator stops at the next row; Step 10’s last test checks that.)
L5 (Lead): A team wants to “go async for performance”. Defend measuring first
What the interviewer is testing: Can you lead a technical decision with evidence, including evidence against the popular answer?
Flip to check your answerFold answer back
Perfect answer: “Performance” has to mean a number for a workload: how many requests, waiting on what, on what machine. Measured on one laptop, three calls to a 2-second partner took about 2 seconds with a sync view and with an async one, because a threaded server already waits concurrently; sixty took slightly longer, and the async view was slower, because it set up a client per request. Both used about a thread per request, because Django still runs its own sync code in a thread under ASGI. So I would not convert the application for speed. I would use async where it changes what is possible: cancelling a wait nobody is watching, streaming under ASGI, holding WebSockets open. I would keep the measuring script, rerun it when Django, the server, or the workload changes, and leave capacity to a proper load test, which this book does in Chapter 66.
Figure 53.8 — Measuring before choosing.
Behind the scenes:
Output
3 calls, 2 s partner about 2 s, either view
60 calls async slower: a client each
threads about one per request, both
Code proof: the eight timings, from Step 11:
Output
daphne sync 3 calls 2.2 s 5 threads
daphne sync 60 calls 2.4 s 62 threads
daphne async 3 calls 2.3 s 5 threads
daphne async 60 calls 3.2 s 62 threads
uvicorn sync 3 calls 2.2 s 5 threads
uvicorn sync 60 calls 2.4 s 62 threads
uvicorn async 3 calls 2.3 s 5 threads
uvicorn async 60 calls 3.2 s 62 threads
Common mistakes:
Quoting a benchmark from another framework or another workload.
Stating a number without the machine, the workload, and the date.
Follow-up the interviewer might ask:
What would make the async view win? (Many waits inside one request, run together with asyncio.gather(), or so many slow calls that the thread pool runs out, which a real load test would show.)
Next: Chapter 54, Channels and real-time updates, keeps the connection open: places left, announcements, and the door count reach open pages as they change, over WebSockets on the same ASGI server.