之前写过一篇使用FastAPI开发流式接口的文章,链接是这里.
这次,再来谈一下使用FastAPI开发流式接口时候的一些问题。
本次我们使用简单点的方式,代码如下
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
async def fake_video_streamer():
for i in range(10):
yield b"some fake video bytes"
@app.get("/")
async def main():
return StreamingResponse(fake_video_streamer())
部署起来之后,使用curl命令来访问,可以看到正常的流式返回,比较流畅,但是如果你的服务部署在HTTPS之后,有一定概率会发现,使用python的requests库请求的时候,返回的内容是成块的,一段一段,而不是流畅的流式响应。
这时候需要进行一些调整,增加一些控制字,修复后的代码如下:
@app.get("/")
async def main():
response = StreamingHttpResponse(
streaming_content=fake_video_streamer(), content_type="text/event-stream"
)
response["Cache-Control"] = "no-cache"
response["X-Accel-Buffering"] = "no"
return response
如果遇到类似问题的小伙伴,可以尝试一下。