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

Patricia Arquette
Release: 2024-10-24 04:46:01
Original
945 people have browsed it

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

Custom 404 Not Found Page with FastAPI

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

Redirect on 404 Status Code

<br>@app.middleware("http")<br>async def redirect_on_not_found(request: Request, call_next):</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">response = await call_next(request)
if response.status_code == 404:
    return RedirectResponse("https://fastapi.tiangolo.com")
else:
    return response
Copy after login

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

Custom Exception Handler for 404

<br>@app.exception_handler(404)<br>async def not_found_exception_handler(request: Request, exc: HTTPException):</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">return RedirectResponse('https://fastapi.tiangolo.com')
Copy after login

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

Custom Error Pages Using Templates

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

<br>templates = Jinja2Templates(directory='templates')</p>
<p>exception_handlers = {</p>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">404: not_found_error,
500: internal_error
Copy after login

}

app = FastAPI(exception_handlers=exception_handlers)

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.

The above is the detailed content of How to Create a Custom 404 Not Found Page in FastAPI?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Previous article:Data Analyst Checklist Next article:Can Automation with Selenium Survive Automatic Chrome Updates?
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Latest Issues
Related Topics
More>
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!