W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
你可以Response在你的路徑操作函數(shù)中聲明一個 type 的參數(shù)(就像你可以為 cookie 做的那樣)。
然后您可以在該時間響應對象中設置標頭。
from fastapi import FastAPI, Response
app = FastAPI()
@app.get("/headers-and-object/")
def get_headers(response: Response):
response.headers["X-Cat-Dog"] = "alone in the world"
return {"message": "Hello World"}
然后您可以像往常一樣返回您需要的任何對象(a dict、數(shù)據(jù)庫模型等)。
如果您聲明了 a response_model,它仍將用于過濾和轉換您返回的對象。
FastAPI將使用該臨時響應來提取標頭(還有 cookie 和狀態(tài)代碼),并將它們放在包含您返回的值的最終響應中,由 any 過濾response_model。
您還可以Response在依賴項中聲明參數(shù),并在其中設置標頭(和 cookie)。
也可以在Response直接返回 a 時添加標題。
按照直接返回響應中的說明創(chuàng)建響應,并將標頭作為附加參數(shù)傳遞:
from fastapi import FastAPI
from fastapi.responses import JSONResponse
app = FastAPI()
@app.get("/headers/")
def get_headers():
content = {"message": "Hello World"}
headers = {"X-Cat-Dog": "alone in the world", "Content-Language": "en-US"}
return JSONResponse(content=content, headers=headers)
技術細節(jié)
您也可以使用from starlette.responses import Response或from starlette.responses import JSONResponse。
FastAPI提供相同starlette.responses的fastapi.responses,就像為你的方便,開發(fā)人員。但大多數(shù)可用的響應直接來自 Starlette。
由于Response可以經(jīng)常用于設置標頭和 cookie,F(xiàn)astAPI也在fastapi.Response.
但是,如果您希望瀏覽器中的客戶端能夠看到自定義標頭,則需要使用Starlette 的 CORS 中記錄的參數(shù)將它們添加到 CORS 配置中(在CORS(跨源資源共享)中了解更多信息) 文檔。expose_headers
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: