前言
某些情況下,需要向客戶端返回錯(cuò)誤提示。
這里所謂的客戶端包括前端瀏覽器、其他應(yīng)用程序、物聯(lián)網(wǎng)設(shè)備等。
需要向客戶端返回錯(cuò)誤提示的場景主要如下:
- 客戶端沒有執(zhí)行操作的權(quán)限
- 客戶端沒有訪問資源的權(quán)限
- 客戶端要訪問的項(xiàng)目不存在
- 等等 …
遇到這些情況時(shí),通常要返回?4XX(400 至 499)HTTP 狀態(tài)碼。
4XX?狀態(tài)碼與表示請求成功的?2XX(200 至 299) HTTP 狀態(tài)碼類似。
只不過,4XX?狀態(tài)碼表示客戶端發(fā)生的錯(cuò)誤。
使用?HTTPException
向客戶端返回 HTTP 錯(cuò)誤響應(yīng),可以使用?HTTPException
。
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}
觸發(fā)?HTTPException
HTTPException
?是額外包含了和 API 有關(guān)數(shù)據(jù)的常規(guī) Python 異常。
因?yàn)槭?Python 異常,所以不能?return
,只能?raise
。
如在調(diào)用_路徑操作函數(shù)_里的工具函數(shù)時(shí),觸發(fā)了?HTTPException
,F(xiàn)astAPI 就不再繼續(xù)執(zhí)行_路徑操作函數(shù)_中的后續(xù)代碼,而是立即終止請求,并把?HTTPException
?的 HTTP 錯(cuò)誤發(fā)送至客戶端。
在介紹依賴項(xiàng)與安全的章節(jié)中,您可以了解更多用?raise
?異常代替?return
?值的優(yōu)勢。
本例中,客戶端用?ID
?請求的?item
?不存在時(shí),觸發(fā)狀態(tài)碼為?404
?的異常:
raise HTTPException(status_code=404, detail="Item not found")
響應(yīng)結(jié)果
請求為?http://example.com/items/foo
(item_id
?為?「foo」
)時(shí),客戶端會接收到 HTTP 狀態(tài)碼 - 200 及如下 JSON 響應(yīng)結(jié)果:
{
"item": "The Foo Wrestlers"
}
但如果客戶端請求?http://example.com/items/bar
(item_id
?「bar」
?不存在時(shí)),則會接收到 HTTP 狀態(tài)碼 - 404(「未找到」錯(cuò)誤)及如下 JSON 響應(yīng)結(jié)果:
{
"detail": "Item not found"
}
觸發(fā)?
HTTPException
?時(shí),可以用參數(shù)?detail
?傳遞任何能轉(zhuǎn)換為 JSON 的值,不僅限于?str
。
還支持傳遞?dict
、list
?等數(shù)據(jù)結(jié)構(gòu)。
FastAPI?能自動處理這些數(shù)據(jù),并將之轉(zhuǎn)換為 JSON。
添加自定義響應(yīng)頭
有些場景下要為 HTTP 錯(cuò)誤添加自定義響應(yīng)頭。例如,出于某些方面的安全需要。
一般情況下可能不會需要在代碼中直接使用響應(yīng)頭。
但對于某些高級應(yīng)用場景,還是需要添加自定義響應(yīng)頭:文章來源:http://www.zghlxwxcb.cn/news/detail-727062.html
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items-header/{item_id}")
async def read_item_header(item_id: str):
if item_id not in items:
raise HTTPException(
status_code=404,
detail="Item not found",
headers={"X-Error": "There goes my error"},
)
return {"item": items[item_id]}
響應(yīng)結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-727062.html
HTTP/1.1 404 Not Found
date: Sun, 24 Sep 2023 01:31:18 GMT
server: uvicorn
x-error: There goes my error
content-length: 27
content-type: application/json
{"detail":"Item not found"}
到了這里,關(guān)于FastAPI學(xué)習(xí)-22.response 異常處理 HTTPException的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!