[英]How to restrict content-type in FastAPI request header
我對 FastAPI 框架很陌生,我想用“application/vnd.api+json”限制我的請求 header 內容類型,但我無法找到使用快速 API 路由配置我的內容類型的方法實例。
任何信息都會非常有用。
每個請求的標頭中都有content-type
。 你可以像這樣檢查它:
import uvicorn
from fastapi import FastAPI, HTTPException
from starlette import status
from starlette.requests import Request
app = FastAPI()
@app.get("/hello")
async def hello(request: Request):
content_type = request.headers.get("content-type", None)
if content_type != "application/vnd.api+json":
raise HTTPException(
status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
detail=f"Unsupported media type {content_type}")
return {"content-type": content_type}
if __name__ == '__main__':
uvicorn.run("main", host="127.0.0.1", port=8080)
希望有幫助
更好的方法是聲明依賴:
from fastapi import FastAPI, HTTPException, status, Header, Depends
app = FastAPI()
def application_vnd(content_type: str = Header(...)):
"""Require request MIME-type to be application/vnd.api+json"""
if content_type != "application/vnd.api+json":
raise HTTPException(
status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
f"Unsupported media type: {content_type}."
" It must be application/vnd.api+json",
)
@app.post("/some-path", dependencies=[Depends(application_vnd)])
def some_path(q: str = None):
return {"result": "All is OK!", "q": q}
因此,如果需要,它可以重復使用。
對於成功的請求,它將返回如下內容:
{
"result": "All is OK!",
"q": "Some query"
}
對於這樣的不成功的事情:
{
"detail": "Unsupported media type: type/unknown-type. It must be application/vnd.api+json"
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.