异步中间件处理流式响应与请求取消
利用 ASGI 中间件实现请求生命周期内的流式读写与客户端断开检测。 · 难度:入门 · +10XP
异步中间件处理流式响应与请求取消
常见中间件教程仅涉及同步处理。本课深入 ASGI 的 scope/receive/send 协议,编写异步中间件来包装 StreamingHttpResponse,支持在生成流式内容时检测客户端是否断开,从而释放资源。你将学习如何监听 receive 通道中的 'http.disconnect' 消息,并配合 async generator 优雅中止。
# middleware.py
from django.http import StreamingHttpResponse
class DisconnectAwareMiddleware:
def __init__(self, get_response):
self.get_response = get_response
async def __call__(self, request):
response = await self.get_response(request)
if isinstance(response, StreamingHttpResponse):
original_stream = response.streaming_content
async def safe_stream():
async for chunk in original_stream:
# 检查客户端是否断开 (需配合ASGI)
if hasattr(request, 'disconnected') and request.disconnected:
break
yield chunk
response.streaming_content = safe_stream()
return response