To create a custom 404 Not Found page, FastAPI offers several approaches. The appropriate method depends on your specific requirements.
<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
This middleware checks the response status code and redirects to a custom page if the code is 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')
A custom exception handler can be created specifically for the 404 status code. This allows for a more specific and targeted response.
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
}
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!