Performance: ASGI vs WSGI
This affects how quickly a Django app can respond to requests and handle multiple users at once.
Jump into concepts and practice - no test required
import asyncio from django.core.asgi import get_asgi_application async def application(scope, receive, send): # ASGI asynchronous app await send({ 'type': 'http.response.start', 'status': 200, 'headers': [(b'content-type', b'text/plain')], }) await send({ 'type': 'http.response.body', 'body': b'Hello World', })
def application(environ, start_response): # WSGI synchronous app response_body = 'Hello World' start_response('200 OK', [('Content-Type', 'text/plain')]) return [response_body.encode('utf-8')]
| Pattern | Concurrency | Blocking Behavior | Latency Under Load | Verdict |
|---|---|---|---|---|
| WSGI (Synchronous) | Single request per worker | Blocks on each request | High latency with many users | [X] Bad |
| ASGI (Asynchronous) | Multiple concurrent requests | Non-blocking async handling | Low latency even under load | [OK] Good |
WSGI and ASGI in Django?asgi.py file?get_asgi_application() to create the ASGI application instance.get_wsgi_application() is for WSGI, others are incorrect function names.from channels.generic.websocket import AsyncWebsocketConsumer
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()connect method is called automatically on WebSocket connection attempts.await self.accept() accepts the WebSocket connection asynchronously, enabling message exchange.asgi.py file but get an error:from django.core.asgi import get_asgi_application application = get_wsgi_application()
get_asgi_application but calls get_wsgi_application(), which is not imported.get_wsgi_application is undefined in this context.