FastAPI 進階知識(六) 定製Response
阿新 • • 發佈:2020-07-13
作者:麥克煎蛋 出處:https://www.cnblogs.com/mazhiyong/ 轉載請保留這段宣告,謝謝!
預設情況下,FastAPI會基於JSONResponse
來返回Response。
如果我們直接返回Response
,資料格式不會被自動轉換,並且互動式文件也不會自動生成。
下面是一些常用的Response型別。
Response
Response主類,所有其他的Response都繼承自這個類。
它接收以下引數資訊:
content
-str
或者bytes
.status_code
- HTTP 狀態碼.headers
- 字串字典.media_type
- media type. 例如"text/html"
FastAPI會自動包含Content-Length,以及Content-Type,charset等頭資訊。
from fastapi import FastAPI, Response app = FastAPI() @app.get("/legacy/") def get_legacy_data(): data = """<?xml version="1.0"?> <shampoo> <Header> Apply shampoo here. </Header> <Body> You'll have to use soap here. </Body> </shampoo>""" return Response(content=data, media_type="application/xml")
我們可以在路徑操作裝飾器中宣告要返回的具體Response
型別,返回的內容會被放入到指定的Response
中
。
並且如果我們指定的Response
支援JSON media型別,例如
JSONResponse
或者UJSONResponse
,那麼返回的資料就會被自動轉換成Pydantic模型(通過response_model
指定)。
HTMLResponse
接收文字或者位元組內容,返回HTML reponse。
from fastapi import FastAPIfrom fastapi.responses import HTMLResponse app = FastAPI() @app.get("/items/", response_class=HTMLResponse) async def read_items(): return """ <html> <head> <title>Some HTML in here</title> </head> <body> <h1>Look ma! HTML!</h1> </body> </html> """
PlainTextResponse
接收文字或者位元組內容,返回純文字 reponse。
from fastapi import FastAPI from fastapi.responses import PlainTextResponse app = FastAPI() @app.get("/", response_class=PlainTextResponse) async def main(): return "Hello World"
JSONResponse
返回application/json
格式的response。FastAPI預設返回的response。
RedirectResponse
返回HTTP重定向。預設狀態碼為307(臨時重定向)。
from fastapi import FastAPI from fastapi.responses import RedirectResponse app = FastAPI() @app.get("/typer") async def read_typer(): return RedirectResponse("https://typer.tiangolo.com")
StreamingResponse
接收一個非同步的發生器或者普通的發生器/列舉器,對返回結果流式輸出。
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())
如果我們有一個file-like物件(比如用open()開啟),我們就可以用StreamingResponse
來返回該物件。
from fastapi import FastAPI from fastapi.responses import StreamingResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") def main(): file_like = open(some_file_path, mode="rb"return StreamingResponse(file_like, media_type="video/mp4")
FileResponse
非同步流式輸出一個檔案。
不同於其他response的初始化引數資訊:
path
- 檔案路徑headers
- 定製頭資訊,字典格式media_type
- media type,如果沒有設定則會根據檔名或檔案路徑來推斷media typefilename
- 檔名。如果設定,會被包含到response的Content-Disposition中
檔案response會包含合適的Content-Length
, Last-Modified
以及 ETag
頭資訊內容。
from fastapi import FastAPI from fastapi.responses import FileResponse some_file_path = "large-video-file.mp4" app = FastAPI() @app.get("/") async def main(): return FileResponse(some_file_path)