Django异步视图与ASGI流式响应:构建ChatGPT式流输出
利用Django 3.1+的原生异步视图和StreamingHttpResponse,实现大语言模型结果逐字输出到前端。涵盖asgiref sync_to_async、数据库异步查询、StreamingHttpResponse与SSE协议的结合,以及异步中间件编写。 · 难度:入门 · +10XP
Django异步视图与ASGI流式响应:构建ChatGPT式流输出
本教程将Django部署于ASGI模式,使用async def视图配合StreamingHttpResponse实现不阻塞的事件流。你将学习如何用sync_to_async封装OpenAI等同步库调用,并通过asyncio.Queue将AI响应分段推送给前端(Server-Sent Events)。还包括异步上下文管理器和取消请求的处理。
from django.http import StreamingHttpResponse
import asyncio
async def stream_view(request):
async def event_stream():
async for token in ai_generate(prompt):
yield f"data: {token}
"
await asyncio.sleep(0.01)
return StreamingHttpResponse(event_stream(), content_type='text/event-stream')