首页  >  文章  >  后端开发  >  如何在 FastAPI 中处理自定义 404 Not Found 响应?

如何在 FastAPI 中处理自定义 404 Not Found 响应?

DDD
DDD原创
2024-10-24 02:06:29910浏览

How to Handle Custom 404 Not Found Responses in FastAPI?

如何使用 FastAPI 返回自定义 404 未找到页面?

当您遇到 404 响应状态代码时,默认错误页面是通常显示在 Web 应用程序中。但是,您可能希望提供自定义 404 页面以获得更加个性化的体验。使用 FastAPI,实现自定义 404 页面非常简单。

自定义异常处理程序

一种有效的方法是利用自定义异常处理程序。通过指定要处理的状态代码,您可以创建目标处理程序。

<code class="python">from fastapi.responses import RedirectResponse
from fastapi.exceptions import HTTPException

@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/404')</code>

异常处理程序参数

或者,您可以使用Exception_handlers参数FastAPI 类。

<code class="python">from fastapi import FastAPI, Request

def not_found_error(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/404')

exception_handlers = {404: not_found_error}
app = FastAPI(exception_handlers=exception_handlers)</code>

注意: 在这些示例中,执行了重定向。但是,您可以根据需要返回任何自定义 Response、HTMLResponse 或 Jinja2 TemplateResponse。

工作示例

考虑以下示例:

app.py

<code class="python">from fastapi.responses import RedirectResponse
from fastapi.exceptions import HTTPException
from fastapi import Request

async def not_found_error(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/404')

async def internal_error(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/500')

exception_handlers = {404: not_found_error, 500: internal_error}
app = FastAPI(exception_handlers=exception_handlers)</code>

404.html模板

<code class="html"><!DOCTYPE html>
<html>
<title>404 Not Found</title>
<body>
<h1>Not Found</h1>
<p>The requested resource could not be found.</p>
</body>
</html></code>

500.html模板

<code class="html"><!DOCTYPE html>
<html>
<title>500 Internal Server Error</title>
<body>
<h1>Internal Server Error</h1>
<p>An internal error has occurred. Please try again later.</p>
</body>
</html></code>

以上是如何在 FastAPI 中处理自定义 404 Not Found 响应?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn