如何在 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中文网其他相关文章!

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

Atom编辑器mac版下载
最流行的的开源编辑器

SublimeText3汉化版
中文版,非常好用

WebStorm Mac版
好用的JavaScript开发工具

Dreamweaver Mac版
视觉化网页开发工具