作用
采用异步生成器或普通生成器(generator)/迭代器(iterator)流式传输响应数据
实际代码
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
file_path = "test.mp4"
app = FastAPI()
@app.get("/")
def main():
# 这是生成器函数。它是一个“生成器函数”,因为它里面包含了 yield 语句
def iterfile():
# 通过使用 with 块,确保在生成器函数完成后关闭类文件对象
with open(file_path, "rb") as file_like:
# yield from 告诉函数迭代名为 file_like 的东西
# 对于迭代的每个部分,yield 的内容作为来自这个生成器函数
yield from file_like
return StreamingResponse(iterfile(), media_type="video/mp4")
返回了视频啦!
源码
异步流式传输文件作为响应,重点一定是异步的
from fastapi import FastAPI
from fastapi.responses import FileResponse
file_path = "test.mp4"
app = FastAPI()
@app.get("/file", response_class=FileResponse)
async def main():
return file_path
感觉这个比 StreamimgResponse 简单多了
和上面 StreamingResponse 一样,也返回了视频啦!