更多自定義響應類型
StreamingResponse
作用
采用異步生成器或普通生成器(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")
- 如果有一個類文件對象(例如 open() 返回的對象),可以創建一個生成器函數來迭代該類文件對象
- 這樣,不必首先在內存中讀取所有內容,可以將該生成器函數傳遞給 StreamingResponse,然后返回它
- 這包括許多與雲存儲、視頻處理等交互的庫
請求結果
返回了視頻啦!
源碼
FileResponse
作用
異步流式傳輸文件作為響應,重點一定是異步的
實際代碼
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 一樣,也返回了視頻啦!
源碼