Async Django
last modified November 21, 2026 Python 3.15
Django supports asynchronous views: a view defined with async def is a coroutine that can await other
coroutines, for example network requests or asyncio.sleep(), and the event loop runs other work while it waits. Async
views help when a view spends its time waiting, above all when it waits for several things at once. Django runs them under both kinds of
servers: WSGI servers, such as runserver, and ASGI servers, such as Uvicorn and Daphne, which run an event loop. In this
article we write async views, compare them with sync views, run the project under ASGI, stream a response, use the async interface of
the ORM, call synchronous code from async views, and test them. The examples use Django 6.1 and Python 3.15.
The example project
The project is created with uv; the steps are explained in
Django introduction. The commands below create a project
directory, install Django together with httpx, generate the project with the configuration package
config, start the app store, and create the folder demos for demo scripts.
$ mkdir shop $ cd shop $ uv init --bare $ uv add django httpx $ uv run django-admin startproject config . $ uv run python manage.py startapp store $ mkdir demos
The trailing dot in startproject config . creates manage.py and the config package in the current
directory instead of one level deeper. The package httpx is an HTTP client with a synchronous and an asynchronous
interface. The new app is added to INSTALLED_APPS in config/settings.py; the other entries are generated by
startproject. At the end of the file we add SERVICES_URL, the address of the services that a later view calls.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'store',
]
...
SERVICES_URL = 'http://127.0.0.1:8000/api/'
The listings in this article are of two kinds. A listing with a solid blue border and the label
Project file is a file of the application: models, views, templates, tests, and
settings. A listing with a dashed amber border and the label Demo script is a small
helper in the demos folder; it sets up Django, runs a few lines of code, and prints
the results, so that we can watch the behaviour. Demo scripts are not part of the application;
we run one from the project directory with uv run python -m demos.name.
A first async view
Real applications wait for databases, other web services, and files. To have something slow to wait for, the module
store/api.py imitates three web services: weather, exchange rates, and news. Each one answers after a fixed delay.
import asyncio
from django.http import Http404, JsonResponse
SERVICES = {
'weather': {'delay': 1.0, 'data': {'city': 'Bratislava', 'temperature': 7}},
'rates': {'delay': 0.5, 'data': {'EUR/USD': 1.16, 'EUR/CZK': 24.3}},
'news': {'delay': 1.5, 'data': {'headline': 'Danube reaches record level'}}
}
async def service(request, name):
if name not in SERVICES:
raise Http404(f'no service {name}')
await asyncio.sleep(SERVICES[name]['delay'])
return JsonResponse(SERVICES[name]['data'])
The view service() is defined with async def. Django checks whether a view is a coroutine function and
calls it accordingly; nothing else has to be registered. await asyncio.sleep() suspends the view without blocking the
thread, unlike time.sleep(). An async view raises Http404 and returns responses the same way as a sync view.
from django.urls import path
from . import api
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
]
The app's URLconf maps the service name to the view, and the project includes the app's URLs.
from django.urls import include, path
urlpatterns = [
path('', include('store.urls')),
]
We start the development server with uv run python manage.py runserver and call the services with curl in a second
terminal. The option -w prints the total time of the request. Each service answers after its delay.
$ curl -s localhost:8000/api/weather/ -w '\ntime: %{time_total} s\n'
{"city": "Bratislava", "temperature": 7}
time: 1.005478 s
$ curl -s localhost:8000/api/rates/ -w '\ntime: %{time_total} s\n'
{"EUR/USD": 1.16, "EUR/CZK": 24.3}
time: 0.503140 s
$ curl -s localhost:8000/api/news/ -w '\ntime: %{time_total} s\n'
{"headline": "Danube reaches record level"}
time: 1.504068 s
Where views run
To see how Django runs the two kinds of views, the module store/probe.py has a sync and an async view that wait one second
and then report the name of the current thread, whether an event loop is running in it, and the number of threads of the process.
import asyncio
import threading
import time
from django.http import JsonResponse
def report(view):
try:
asyncio.get_running_loop()
loop = True
except RuntimeError:
loop = False
return JsonResponse({'view': view, 'thread': threading.current_thread().name,
'loop': loop, 'threads': threading.active_count()})
def sync_view(request):
time.sleep(1)
return report('sync')
async def async_view(request):
await asyncio.sleep(1)
return report('async')
The URLconf gets the two probe views.
from django.urls import path
from . import api, probe
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
path('probe/sync/', probe.sync_view),
path('probe/async/', probe.async_view),
]
runserver is a WSGI server: it handles each request in a new thread and calls the application synchronously. The sync view
runs in that request thread. For the async view, Django starts an event loop in another thread, a worker of a thread pool, and waits
until the coroutine finishes, so the request thread is blocked for the whole second anyway. Under WSGI, an async view gives no
advantage for a single wait; it pays off only when the view waits for several things concurrently.
$ curl -s localhost:8000/probe/sync/
{"view": "sync", "thread": "Thread-2 (process_request_thread)", "loop": false, "threads": 2}
$ curl -s localhost:8000/probe/async/
{"view": "async", "thread": "ThreadPoolExecutor-1_0", "loop": true, "threads": 3}
Calling services one after another
A dashboard page needs the data of all three services. The sync view dashboard_sync() calls them with the synchronous
httpx.Client, one after another. The base_url comes from the setting SERVICES_URL; in our
project, the services run on the same server.
import httpx
from django.conf import settings
from django.http import JsonResponse
NAMES = ['weather', 'rates', 'news']
def dashboard_sync(request):
data = {}
with httpx.Client(base_url=settings.SERVICES_URL) as client:
for name in NAMES:
response = client.get(f'{name}/')
data[name] = response.json()
return JsonResponse(data)
The URLconf maps the dashboard.
from django.urls import path
from . import api, probe, views
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
path('probe/sync/', probe.sync_view),
path('probe/async/', probe.async_view),
path('dashboard/sync/', views.dashboard_sync),
]
The times of the calls add up: 1 + 0.5 + 1.5 seconds, plus a little overhead.
$ curl -s localhost:8000/dashboard/sync/ -w '\ntime: %{time_total} s\n'
{"weather": {"city": "Bratislava", "temperature": 7}, "rates": {"EUR/USD": 1.16, "EUR/CZK": 24.3}, "news": {"headline": "Danube reaches record level"}}
time: 3.172308 s
Calling services concurrently
The async view dashboard() uses httpx.AsyncClient. The coroutine fetch() requests one service;
asyncio.gather() runs the three coroutines concurrently and returns their results in the order of the arguments, so
zip() pairs them with the names.
import asyncio
import httpx
from django.conf import settings
from django.http import JsonResponse
NAMES = ['weather', 'rates', 'news']
def dashboard_sync(request):
data = {}
with httpx.Client(base_url=settings.SERVICES_URL) as client:
for name in NAMES:
response = client.get(f'{name}/')
data[name] = response.json()
return JsonResponse(data)
async def fetch(client, name):
response = await client.get(f'{name}/')
return response.json()
async def dashboard(request):
async with httpx.AsyncClient(base_url=settings.SERVICES_URL) as client:
results = await asyncio.gather(*(fetch(client, name) for name in NAMES))
return JsonResponse(dict(zip(NAMES, results)))
The URLconf gets the async dashboard.
from django.urls import path
from . import api, probe, views
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
path('probe/sync/', probe.sync_view),
path('probe/async/', probe.async_view),
path('dashboard/sync/', views.dashboard_sync),
path('dashboard/', views.dashboard),
]
The view now waits only as long as the slowest service, 1.5 seconds. This works under runserver too, because the
concurrency happens inside the event loop of the view.
$ curl -s localhost:8000/dashboard/ -w '\ntime: %{time_total} s\n'
{"weather": {"city": "Bratislava", "temperature": 7}, "rates": {"EUR/USD": 1.16, "EUR/CZK": 24.3}, "news": {"headline": "Danube reaches record level"}}
time: 1.584035 s
Running under ASGI with Uvicorn
ASGI is the asynchronous counterpart of WSGI. An ASGI server runs an event loop and calls the application as a coroutine. The module
config/asgi.py was generated by startproject; it creates the application object that the server loads.
"""
ASGI config for config project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
application = get_asgi_application()
Uvicorn is a popular ASGI server. We install it with uv add uvicorn, stop runserver, and start Uvicorn with
the path to the application object. It listens on port 8000 by default. The line about the lifespan protocol is normal: Django does
not implement the startup and shutdown events of ASGI. Unlike runserver, Uvicorn neither reloads changed code (unless started
with --reload) nor serves static files.
$ uv add uvicorn $ uv run uvicorn config.asgi:application INFO: Started server process [45843] 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)
Views under Uvicorn
We call the probe views and the dashboard again. Under ASGI, the async view runs directly in the event loop of the server, in the main
thread. The sync view cannot run in the event loop, because it would block it; Django runs it in a worker thread with
sync_to_async() and awaits the result.
$ curl -s localhost:8000/probe/sync/
{"view": "sync", "thread": "ThreadPoolExecutor-2_0", "loop": false, "threads": 2}
$ curl -s localhost:8000/probe/async/
{"view": "async", "thread": "MainThread", "loop": true, "threads": 2}
$ curl -s localhost:8000/dashboard/ -w '\ntime: %{time_total} s\n'
{"weather": {"city": "Bratislava", "temperature": 7}, "rates": {"EUR/USD": 1.16, "EUR/CZK": 24.3}, "news": {"headline": "Danube reaches record level"}}
time: 1.548784 s
Many requests at once
Does the async view need fewer threads? The demo script demos/load.py sends many requests to a URL at the same time with
httpx.AsyncClient and prints the elapsed time and the largest thread count that the responses reported. It does not need
Django, so it skips django.setup(); it runs while Uvicorn is running.
import asyncio
import sys
import time
import httpx
async def main(url, count):
async with httpx.AsyncClient(timeout=30) as client:
start = time.perf_counter()
responses = await asyncio.gather(*(client.get(url) for _ in range(count)))
elapsed = time.perf_counter() - start
threads = max(response.json()['threads'] for response in responses)
print(f'{count} requests in {elapsed:.2f} s, up to {threads} threads')
asyncio.run(main(sys.argv[1], int(sys.argv[2])))
Both views handle 50 requests in about one second, and both use one thread per request. For the sync view this is expected. For the
async view, the thread comes from Django itself: for every request, the ASGI handler of Django 6.1 creates a thread-sensitive context
and sends the request_started signal, whose receivers are synchronous; they run in a new thread that belongs to the
request and lives until the request ends. So in Django 6.1, async views do not save threads. Their advantage is the concurrency inside a
view, as in the dashboard, and long-running responses such as streams, which follow.
$ uv run python -m demos.load http://localhost:8000/probe/sync/ 50 50 requests in 1.10 s, up to 51 threads $ uv run python -m demos.load http://localhost:8000/probe/async/ 50 50 requests in 1.10 s, up to 51 threads
Streaming responses
StreamingHttpResponse sends the content piece by piece. Its content can be an asynchronous generator: the coroutine
ticks() yields a line every second. Django sets the process time zone to TIME_ZONE, which is UTC by default,
so time.strftime() prints UTC time.
import asyncio
import time
import httpx
from django.conf import settings
from django.http import JsonResponse, StreamingHttpResponse
NAMES = ['weather', 'rates', 'news']
def dashboard_sync(request):
data = {}
with httpx.Client(base_url=settings.SERVICES_URL) as client:
for name in NAMES:
response = client.get(f'{name}/')
data[name] = response.json()
return JsonResponse(data)
async def fetch(client, name):
response = await client.get(f'{name}/')
return response.json()
async def dashboard(request):
async with httpx.AsyncClient(base_url=settings.SERVICES_URL) as client:
results = await asyncio.gather(*(fetch(client, name) for name in NAMES))
return JsonResponse(dict(zip(NAMES, results)))
async def ticks(count):
for i in range(1, count + 1):
yield f'tick {i} at {time.strftime("%H:%M:%S")}\n'
await asyncio.sleep(1)
async def clock(request):
return StreamingHttpResponse(ticks(3), content_type='text/plain')
The URLconf maps the clock.
from django.urls import path
from . import api, probe, views
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
path('probe/sync/', probe.sync_view),
path('probe/async/', probe.async_view),
path('dashboard/sync/', views.dashboard_sync),
path('dashboard/', views.dashboard),
path('clock/', views.clock),
]
The option -N turns off the output buffer of curl, and the shell loop prefixes every line with the time when the client
received it (date -u prints UTC as well). Under Uvicorn every tick arrives right when it is produced.
$ curl -sN localhost:8000/clock/ | while read line; do echo "$(date -u +%T) $line"; done 19:42:12 tick 1 at 19:42:12 19:42:13 tick 2 at 19:42:13 19:42:14 tick 3 at 19:42:14
Streaming under WSGI
A WSGI server iterates the response synchronously. When we stop Uvicorn and run the clock under runserver, Django has to
collect the whole asynchronous generator before it sends anything: the three ticks are produced one second apart, but the client gets
them all at once after three seconds. The server terminal shows a warning about it. Streaming with async generators needs an ASGI server.
$ curl -sN localhost:8000/clock/ | while read line; do echo "$(date -u +%T) $line"; done 19:42:18 tick 1 at 19:42:15 19:42:18 tick 2 at 19:42:16 19:42:18 tick 3 at 19:42:17 $ uv run python manage.py runserver ... /home/user/.local/share/uv/python/cpython-3.15.2-linux-x86_64-gnu/lib/python3.15/wsgiref/handlers.py:184: Warning: StreamingHttpResponse must consume asynchronous iterators in order to serve them synchronously. Use a synchronous iterator instead. for data in self.result: [21/Nov/2026 19:42:18] "GET /clock/ HTTP/1.1" 200 57
Daphne and runserver
Daphne is the ASGI server of the Django Channels project. Besides running as a standalone server, it can replace the WSGI server of
runserver, so development keeps the code reloading and the static files of runserver. We install it with
uv add daphne, put 'daphne' first in INSTALLED_APPS, so that its runserver command
overrides the one of django.contrib.staticfiles, and set ASGI_APPLICATION, which tells Daphne where the
application object is.
INSTALLED_APPS = [
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'store',
]
...
WSGI_APPLICATION = 'config.wsgi.application'
ASGI_APPLICATION = 'config.asgi.application'
runserver now announces an ASGI/Daphne server. The async view runs in the main thread, as under Uvicorn, and the 50
requests take about one second. The rest of the article uses this server.
$ uv add daphne
$ uv run python manage.py runserver
...
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 CONTROL-C.
$ curl -s localhost:8000/probe/sync/
{"view": "sync", "thread": "ThreadPoolExecutor-2_0", "loop": false, "threads": 3}
$ curl -s localhost:8000/probe/async/
{"view": "async", "thread": "MainThread", "loop": true, "threads": 3}
$ uv run python -m demos.load http://localhost:8000/probe/async/ 50
50 requests in 1.12 s, up to 52 threads
A model
The async parts of the ORM are shown on products in categories. The relation from a product to its category matters later, because Django loads related objects lazily.
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name='products')
price = models.DecimalField(max_digits=8, decimal_places=2)
stock = models.PositiveIntegerField(default=0)
class Meta:
ordering = ['name']
def __str__(self):
return self.name
We create and apply the migrations.
$ uv run python manage.py makemigrations store
Migrations for 'store':
store/migrations/0001_initial.py
+ Create model Category
+ Create model Product
$ uv run python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, store
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Applying store.0001_initial... OK
Sample data
The demo script demos/seed.py fills the database with three categories and seven products. It is ordinary synchronous
code; the ORM works the usual way outside an event loop.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from store.models import Category, Product
PRODUCTS = {
'Books': [('Dune', '12.90', 8), ('Solaris', '9.50', 0), ('Neuromancer', '11.20', 3)],
'Games': [('Chess set', '24.00', 5), ('Go board', '39.90', 2)],
'Music': [('Kind of Blue', '19.99', 0), ('Blue Train', '17.50', 6)],
}
Product.objects.all().delete()
Category.objects.all().delete()
for category_name, products in PRODUCTS.items():
category = Category.objects.create(name=category_name)
for name, price, stock in products:
Product.objects.create(name=name, category=category, price=price, stock=stock)
print(Category.objects.count(), 'categories,', Product.objects.count(), 'products')
The script deletes the old rows first, so it can be run again. The products get ids 1 to 7 in a fresh database.
$ uv run python -m demos.seed 3 categories, 7 products
The async ORM
The QuerySet methods that run a query have async variants with the prefix a: aget(),
acount(), afirst(), aupdate(), acreate(), adelete(),
aexists(), and others. Methods that only build a query, such as filter() and order_by(), do not
touch the database and stay the same. A QuerySet is iterated with async for. asyncio.run() starts an event
loop for the coroutine main().
import asyncio
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from store.models import Product
async def main():
print('products:', await Product.objects.acount())
dune = await Product.objects.aget(name='Dune')
print('found:', dune, dune.price)
print('low stock:')
async for product in Product.objects.filter(stock__lt=3):
print(' ', product.name, product.stock)
updated = await Product.objects.filter(name='Solaris').aupdate(stock=4)
print('restocked:', updated)
first = await Product.objects.order_by('-price').afirst()
print('most expensive:', first, first.price)
asyncio.run(main())
In Django 6.1 the database backends are synchronous; the async methods run the query in a worker thread with
sync_to_async(). The code does not get faster, but it does not block the event loop. aupdate() returns the
number of changed rows: Solaris is back in stock.
$ uv run python -m demos.async_orm products: 7 found: Dune 12.90 low stock: Go board 2 Kind of Blue 0 Solaris 0 restocked: 1 most expensive: Go board 39.90
SynchronousOnlyOperation
Django refuses to run a database query directly in an event loop, because it would block the loop. A query in an async context raises
SynchronousOnlyOperation. Two common cases are hidden queries: reading a foreign key that was not loaded, and iterating a
QuerySet with a plain for, which also happens in a list comprehension.
import asyncio
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from store.models import Product
async def main():
dune = await Product.objects.aget(name='Dune')
try:
print(dune.category)
except Exception as e:
print(type(e).__name__ + ':', e)
try:
names = [product.name for product in Product.objects.all()]
except Exception as e:
print(type(e).__name__ + ':', e)
dune = await Product.objects.select_related('category').aget(name='Dune')
print('category:', dune.category)
names = [product.name async for product in Product.objects.all()]
print('names:', names)
asyncio.run(main())
select_related('category') loads the category with the product in one query, so reading dune.category needs
no further query. An asynchronous comprehension, [... async for ...], builds the list in the event loop.
$ uv run python -m demos.sync_only SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. category: Books names: ['Blue Train', 'Chess set', 'Dune', 'Go board', 'Kind of Blue', 'Neuromancer', 'Solaris']
Async views and the ORM
The views product_list() and product_detail() return products as JSON. The helper
product_data() reads product.category.name, so both views fetch the category with
select_related(). aget_object_or_404() is the async variant of get_object_or_404(); it takes a
model or a QuerySet.
import asyncio
import time
import httpx
from django.conf import settings
from django.http import JsonResponse, StreamingHttpResponse
from django.shortcuts import aget_object_or_404
from .models import Product
NAMES = ['weather', 'rates', 'news']
def dashboard_sync(request):
data = {}
with httpx.Client(base_url=settings.SERVICES_URL) as client:
for name in NAMES:
response = client.get(f'{name}/')
data[name] = response.json()
return JsonResponse(data)
async def fetch(client, name):
response = await client.get(f'{name}/')
return response.json()
async def dashboard(request):
async with httpx.AsyncClient(base_url=settings.SERVICES_URL) as client:
results = await asyncio.gather(*(fetch(client, name) for name in NAMES))
return JsonResponse(dict(zip(NAMES, results)))
async def ticks(count):
for i in range(1, count + 1):
yield f'tick {i} at {time.strftime("%H:%M:%S")}\n'
await asyncio.sleep(1)
async def clock(request):
return StreamingHttpResponse(ticks(3), content_type='text/plain')
def product_data(product):
return {'id': product.id, 'name': product.name, 'category': product.category.name,
'price': str(product.price), 'stock': product.stock}
async def product_list(request):
products = Product.objects.select_related('category')
if 'category' in request.GET:
products = products.filter(category__name=request.GET['category'])
data = [product_data(product) async for product in products]
return JsonResponse({'products': data})
async def product_detail(request, pk):
product = await aget_object_or_404(Product.objects.select_related('category'), pk=pk)
return JsonResponse(product_data(product))
The URLconf gets the two product URLs.
from django.urls import path
from . import api, probe, views
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
path('probe/sync/', probe.sync_view),
path('probe/async/', probe.async_view),
path('dashboard/sync/', views.dashboard_sync),
path('dashboard/', views.dashboard),
path('clock/', views.clock),
path('products/', views.product_list),
path('products/<int:pk>/', views.product_detail),
]
We filter the list by category, fetch the chess set, and ask for a product that does not exist; the option -w prints only
the status code of the last request.
$ curl -s "localhost:8000/products/?category=Games"
{"products": [{"id": 4, "name": "Chess set", "category": "Games", "price": "24.00", "stock": 5}, {"id": 5, "name": "Go board", "category": "Games", "price": "39.90", "stock": 2}]}
$ curl -s localhost:8000/products/4/
{"id": 4, "name": "Chess set", "category": "Games", "price": "24.00", "stock": 5}
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/products/100/
404
Calling synchronous code
Not all code is async. The function stock_report() in store/reports.py computes the value of the stock in
each category and lists the sold-out products. It uses the ordinary synchronous ORM, with a plain for loop and the related
manager category.products; such code can also come from a library that we cannot change.
from decimal import Decimal
from .models import Category
def stock_report():
rows = []
for category in Category.objects.order_by('name'):
products = category.products.all()
value = sum((p.price * p.stock for p in products), Decimal('0'))
empty = [p.name for p in products if p.stock == 0]
rows.append({'category': category.name, 'value': str(value), 'sold_out': empty})
return rows
A first attempt imports the function in store/views.py and calls it directly from a new async view. The rest of the
module stays as before.
from .reports import stock_report
...
async def report(request):
rows = stock_report()
return JsonResponse({'report': rows})
The URLconf maps the report.
from django.urls import path
from . import api, probe, views
urlpatterns = [
path('api/<str:name>/', api.service, name='service'),
path('probe/sync/', probe.sync_view),
path('probe/async/', probe.async_view),
path('dashboard/sync/', views.dashboard_sync),
path('dashboard/', views.dashboard),
path('clock/', views.clock),
path('products/', views.product_list),
path('products/<int:pk>/', views.product_detail),
path('report/', views.report),
]
The first query of the report raises SynchronousOnlyOperation, and the request fails with status 500. The shortened
traceback in the server terminal shows where.
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/report/
500
Internal Server Error: /report/
Traceback (most recent call last):
...
File "./store/views.py", line 69, in report
rows = stock_report()
File "./store/reports.py", line 9, in stock_report
for category in Category.objects.order_by('name'):
~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
...
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
sync_to_async
sync_to_async() from the package asgiref, which Django depends on, wraps a synchronous function into an
awaitable one that runs in a worker thread. By default it is thread-sensitive: all such calls of a request run in the same thread,
which matters for database connections and other code that is not thread-safe. The opposite wrapper, async_to_sync(),
runs a coroutine from synchronous code; Django uses it to run async views under WSGI. This is the final version of the views module.
import asyncio
import time
import httpx
from asgiref.sync import sync_to_async
from django.conf import settings
from django.http import JsonResponse, StreamingHttpResponse
from django.shortcuts import aget_object_or_404
from .models import Product
from .reports import stock_report
NAMES = ['weather', 'rates', 'news']
def dashboard_sync(request):
data = {}
with httpx.Client(base_url=settings.SERVICES_URL) as client:
for name in NAMES:
response = client.get(f'{name}/')
data[name] = response.json()
return JsonResponse(data)
async def fetch(client, name):
response = await client.get(f'{name}/')
return response.json()
async def dashboard(request):
async with httpx.AsyncClient(base_url=settings.SERVICES_URL) as client:
results = await asyncio.gather(*(fetch(client, name) for name in NAMES))
return JsonResponse(dict(zip(NAMES, results)))
async def ticks(count):
for i in range(1, count + 1):
yield f'tick {i} at {time.strftime("%H:%M:%S")}\n'
await asyncio.sleep(1)
async def clock(request):
return StreamingHttpResponse(ticks(3), content_type='text/plain')
def product_data(product):
return {'id': product.id, 'name': product.name, 'category': product.category.name,
'price': str(product.price), 'stock': product.stock}
async def product_list(request):
products = Product.objects.select_related('category')
if 'category' in request.GET:
products = products.filter(category__name=request.GET['category'])
data = [product_data(product) async for product in products]
return JsonResponse({'products': data})
async def product_detail(request, pk):
product = await aget_object_or_404(Product.objects.select_related('category'), pk=pk)
return JsonResponse(product_data(product))
async def report(request):
rows = await sync_to_async(stock_report)()
return JsonResponse({'report': rows})
The view awaits the wrapped function, and the report now works. We format the JSON with Python's json.tool module.
$ curl -s localhost:8000/report/ | python3 -m json.tool
{
"report": [
{
"category": "Books",
"value": "174.80",
"sold_out": []
},
{
"category": "Games",
"value": "199.80",
"sold_out": []
},
{
"category": "Music",
"value": "105.00",
"sold_out": [
"Kind of Blue"
]
}
]
}
Testing async views
Django's test case classes accept test methods defined with async def and run them in an event loop. The attribute
self.async_client is an AsyncClient, a test client whose methods are awaited and which calls the views
through the ASGI handler. The data from setUpTestData() and the async ORM calls in the tests are rolled back after each test, as
with sync tests (see Django testing).
from django.test import TestCase
from .models import Category, Product
class StoreTests(TestCase):
@classmethod
def setUpTestData(cls):
games = Category.objects.create(name='Games')
cls.chess = Product.objects.create(name='Chess set', category=games,
price='24.00', stock=5)
async def test_product_detail(self):
response = await self.async_client.get(f'/products/{self.chess.pk}/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json()['category'], 'Games')
async def test_missing_product(self):
response = await self.async_client.get('/products/100/')
self.assertEqual(response.status_code, 404)
async def test_new_product_is_listed(self):
await Product.objects.acreate(name='Go board', category_id=self.chess.category_id,
price='39.90', stock=2)
response = await self.async_client.get('/products/', {'category': 'Games'})
names = [p['name'] for p in response.json()['products']]
self.assertEqual(names, ['Chess set', 'Go board'])
async def test_unknown_service(self):
response = await self.async_client.get('/api/stocks/')
self.assertEqual(response.status_code, 404)
async def test_report(self):
response = await self.async_client.get('/report/')
self.assertEqual(response.json()['report'][0]['value'], '120.00')
The tests do not call the dashboard, which needs a running server for the services.
$ uv run python manage.py test -v 2 2>&1 | grep -v "^ Apply"
Found 5 test(s).
Creating test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
Operations to perform:
Synchronize unmigrated apps: daphne, messages, staticfiles
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Running migrations:
System check identified no issues (0 silenced).
test_missing_product (store.tests.StoreTests.test_missing_product) ... ok
test_new_product_is_listed (store.tests.StoreTests.test_new_product_is_listed) ... ok
test_product_detail (store.tests.StoreTests.test_product_detail) ... ok
test_report (store.tests.StoreTests.test_report) ... ok
test_unknown_service (store.tests.StoreTests.test_unknown_service) ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.024s
OK
Destroying test database for alias 'default' ('file:memorydb_default?mode=memory&cache=shared')...
Source
Django documentation: Asynchronous support
Django documentation: Asynchronous queries
Django documentation: How to deploy with ASGI
HTTPX documentation: Async support
In this article we have written asynchronous views in Django: we called slow services concurrently with
asyncio.gather(), ran the project under Uvicorn and under Daphne's runserver, streamed a response from an
async generator, used the async ORM and avoided SynchronousOnlyOperation, wrapped synchronous code with
sync_to_async(), and tested the views with AsyncClient. Related articles are
Django views, Django QuerySets,
Django query performance, which explains select_related(),
Django testing, and Django Channels and WebSockets, which
uses ASGI for long-lived WebSocket connections.
Author
List all Django tutorials.