python / intermediate
Snippet
Asynchronous View Handler with Concurrent Task Gathering in Django
Django supports native asynchronous views using Python's async/await syntax. Async views can execute non-blocking database calls like `alast()` alongside asynchronous external API tasks using `asyncio.create_task()` to process operations concurrently without blocking the main worker thread.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import asynciofrom django.http import JsonResponsefrom myapp.models import Articleasync def fetch_external_stats():await asyncio.sleep(0.1)return {"status": "ok", "latency_ms": 45}async def get_dashboard_data_view(request):latest_article = await Article.objects.alast()stats_task = asyncio.create_task(fetch_external_stats())stats = await stats_taskreturn JsonResponse({"latest_title": latest_article.title if latest_article else None,"api_stats": stats,})
django
Breakdown
1
import asyncio
Imports Python's standard asynchronous I/O module for concurrent execution.
2
async def fetch_external_stats():
Defines an asynchronous helper function returning external metrics.
3
async def get_dashboard_data_view(request):
Defines an asynchronous Django view handler function.
4
latest_article = await Article.objects.alast()
Asynchronously awaits the fetch of the last database record using Django's async ORM method.
5
stats_task = asyncio.create_task(fetch_external_stats())
Schedules the coroutine to run concurrently on the event loop.
6
stats = await stats_task
Awaits completion of the concurrent stats fetching task.