"Si un trabajador quiere hacer bien su trabajo, primero debe afilar sus herramientas." - Confucio, "Las Analectas de Confucio. Lu Linggong"
Página delantera > Programación > FastAPI自定义404页面创建指南

FastAPI自定义404页面创建指南

Publicado el 2025-04-17
Navegar:401

How to Create a Custom 404 Not Found Page in FastAPI?

<h2>Custom 404 Not Found Page with FastAPI</h2>

To create a custom 404 Not Found page, FastAPI offers several approaches. The appropriate method depends on your specific requirements.

<h3>Redirect on 404 Status Code</h3>

<pre>
@app.middleware("http")
async def redirect_on_not_found(request: Request, call_next):

response = await call_next(request)
if response.status_code == 404:
    return RedirectResponse("https://fastapi.tiangolo.com")
else:
    return response

</pre>

This middleware checks the response status code and redirects to a custom page if the code is 404.

<h3>Custom Exception Handler for 404</h3>

<pre>
@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc: HTTPException):

return RedirectResponse('https://fastapi.tiangolo.com')

</pre>

A custom exception handler can be created specifically for the 404 status code. This allows for a more specific and targeted response.

<h3>Custom Error Pages Using Templates</h3>

FastAPI supports the use of templates to render custom error pages. This example creates two error pages:

<pre>
templates = Jinja2Templates(directory='templates')

exception_handlers = {

404: not_found_error,
500: internal_error

}

app = FastAPI(exception_handlers=exception_handlers)
</pre>

Templates are located in the 'templates' directory and can be customized to your needs.

By selecting the method that best suits your application, you can create a custom 404 Not Found page in FastAPI.

Declaración de liberación Este artículo se reproduce en: 1729692542 Si hay alguna infracción, comuníquese con [email protected] para eliminarlo.
Último tutorial Más>

Descargo de responsabilidad: Todos los recursos proporcionados provienen en parte de Internet. Si existe alguna infracción de sus derechos de autor u otros derechos e intereses, explique los motivos detallados y proporcione pruebas de los derechos de autor o derechos e intereses y luego envíelos al correo electrónico: [email protected]. Lo manejaremos por usted lo antes posible.

Copyright© 2022 湘ICP备2022001581号-3