Async Web Framework: The ASGI Specification
Asynchronous Server Gateway Interface (ASGI) is the modern Python standard connecting async servers (Uvicorn) to frameworks (FastAPI). An ASGI app is an async callable: `app(scope, receive, send)` 🌐.
import asyncio
async def asgi_app(scope, receive, send):
assert scope["type"] == "http"
await send({
"type": "http.response.start",
"status": 200,
"headers": [(b"content-type", b"text/plain")]
})
await send({
"type": "http.response.body",
"body": b"Hello ASGI 🌐"
})
async def test_run():
captured = []
async def send(msg): captured.append(msg)
async def receive(): return {"type": "http.request"}
await asgi_app({"type": "http"}, receive, send)
print(f"Status: {captured[0]['status']}")
print(f"Payload: {captured[1]['body'].decode()} 🌐")
asyncio.run(test_run())
# 113. Async Web Framework: The ASGI Specification Asynchronous Server Gateway Interface (ASGI) is the modern Python standard connecting async servers (Uvicorn) to frameworks (FastAPI). An ASGI app is an async callable: `app(scope, receive, send)` 🌐. ```python import asyncio async def asgi_app(scope, receive, send): assert scope["type"] == "http" await send({ "type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain")] }) await send({ "type": "http.response.body", "body": b"Hello ASGI 🌐" }) async def test_run(): captured = [] async def send(msg): captured.append(msg) async def receive(): return {"type": "http.request"} await asgi_app({"type": "http"}, receive, send) print(f"Status: {captured[0]['status']}") print(f"Payload: {captured[1]['body'].decode()} 🌐") asyncio.run(test_run()) ``` Unlike synchronous WSGI which handles only request-response cycles, ASGI natively supports WebSockets (`scope['type'] == 'websocket'`) and long-lived Server-Sent Events (SSE) 🚀! --- ### Question What three arguments define the core ASGI 3.0 asynchronous application interface? 🧠 - [ ] a. `scope` (connection metadata), `receive` (async event receiver), and `send` (async event dispatcher) 🌐 - [ ] b. `environ`, `start_response`, and `response_headers` (legacy WSGI interface) - [ ] c. `request_stream`, `response_stream`, and `connection_context` - [ ] d. `socket_fd`, `read_buffer`, and `write_buffer` --- ### Challenge Build an ASGI app that responds with status `200` and body `b'PONG'`. Test with mock `send` collecting messages and print `messages[1]['body'].decode()`. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def app(scope, receive, send): await send({'type': 'http.response.start', 'status': 200}) await send({'type': 'http.response.body', 'body': b'PONG'}) async def run(): msgs = [] async def mock_send(m): msgs.append(m) async def mock_recv(): return {} await app({'type': 'http'}, mock_recv, mock_send) print(msgs[1]['body'].decode()) asyncio.run(run()) ``` </details>