如何在 FastAPI 中為特定路由自訂錯誤回應
在 FastAPI 中,引發 RequestValidationError 允許您傳送自訂錯誤回應。這對於需要滿足特定條件(例如必需的標頭)的端點非常有用。
選項 1:覆寫預設異常處理程序
此選項可讓您覆寫預設異常處理程序RequestValidationError,讓您自訂錯誤回應。
from fastapi import FastAPI, Request, Header, status from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() routes_with_custom_exception = ['/'] @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): if request.url.path in routes_with_custom_exception: return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=jsonable_encoder({'detail': exc.errors(), 'body': exc.body}), )
選項 2:使用子應用程式
建立子應用程式可讓您使用自己的異常處理程序建立單獨的 API 實例。這允許您專門為子應用程式自訂錯誤處理。
from fastapi import FastAPI from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse app = FastAPI() subapi = FastAPI() @subapi.exception_handler(RequestValidationError) async def validation_exception_handler(exc: RequestValidationError): return JSONResponse(content={'401': 'Unauthorized'}, status_code=401) @subapi.get('/') async def subapi_route(some_custom_header: str = Header(...)): return {'some-custom-header': some_custom_header} app.mount('/sub', subapi)
選項 3:使用自訂 APIRoute 類別
此方法可讓您更改特定路由的行為透過使用自訂 APIRoute 類別。
from fastapi import FastAPI, APIRouter, Response, Request, Header, HTTPException from fastapi.exceptions import RequestValidationError class ValidationErrorHandlingRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request) -> Response: try: return await original_route_handler(request) except RequestValidationError as e: raise HTTPException(status_code=401, detail='401 Unauthorized') return custom_route_handler app = FastAPI() router = APIRouter(route_class=ValidationErrorHandlingRoute) @router.get('/custom') async def custom_route(some_custom_header: str = Header(...)): return {'some-custom-header': some_custom_header} app.include_router(router)
您應該使用哪個選項?
選項 1當您只需要為特定路由自訂錯誤回應時,實作起來很簡單。當您想要對 API 的子區域進行更多控制(例如套用不同的安全性原則或例外處理)時,選項 2 是適當的。選項 3 可讓您更好地控制各個路線,並且對於處理路線內的特定情況很有用。
以上是如何為特定 FastAPI 路由自訂錯誤回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

pythonexecutionistheprocessoftransformingpypythoncodeintoExecutablestructions.1)InternterPreterReadSthecode,ConvertingTingitIntObyTecode,whepythonvirtualmachine(pvm)theglobalinterpreterpreterpreterpreterlock(gil)the thepythonvirtualmachine(pvm)

Python的關鍵特性包括:1.語法簡潔易懂,適合初學者;2.動態類型系統,提高開發速度;3.豐富的標準庫,支持多種任務;4.強大的社區和生態系統,提供廣泛支持;5.解釋性,適合腳本和快速原型開發;6.多範式支持,適用於各種編程風格。

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。