Django is a Python web framework with substantial functionality included, including an object-relational mapper for databases and a customizable administration console. section 9.4
Django supports both WSGI and ASGI deployment. Version 3.1 added asynchronous views, enabling direct use of asyncio libraries, although async support remains incomplete and the ORM is synchronous. section 9.4
A practical Django application workflow includes:
- Create a project with django-admin, then serve its ASGI application with Uvicorn. section 9.4
- Add an application, register it in INSTALLED_APPS, and connect its URL patterns to the project. section 9.4
- Deploy through either an ASGI or WSGI gateway interface. section 9.4
Concurrent requests view
An asynchronous Django view accepts a URL and request count, uses aiohttp to issue requests concurrently with asyncio.gather, and renders status, response time, body length, and failures in an HTML table. section 9.4 section 9.5
Listing 9.11 A Django asynchronous view
import asyncio
from datetime import datetime
from aiohttp import ClientSession
from django.shortcuts import render
import aiohttp
async def get_url_details(session: ClientSession, url: str):
start_time = datetime.now()
response = await session.get(url)
response_body = await response.text()
end_time = datetime.now()
return {'status': response.status,
'time': (end_time - start_time).microseconds,
'body_length': len(response_body)}
async def make_requests(url: str, request_num: int):
async with aiohttp.ClientSession() as session:
requests = [get_url_details(session, url) for _ in range(request_num)]
results = await asyncio.gather(*requests, return_exceptions=True)
failed_results = [str(result) for result in results if isinstance(result, Exception)]
successful_results = [result for result in results if not isinstance(result, Exception)]
return {'failed_results': failed_results, 'successful_results': successful_results}
async def requests_view(request):
url: str = request.GET['url']
request_num: int = int(request.GET['request_num'])
context = await make_requests(url, request_num)
return render(request, 'async_api/requests.html', context)
Inspect the complete asynchronous view implementation, including request gathering and exception aggregation. section 9.4

