首頁  >  文章  >  後端開發  >  如何在 FastAPI 中建立自訂 404 Not Found 頁面?

如何在 FastAPI 中建立自訂 404 Not Found 頁面?

Patricia Arquette
Patricia Arquette原創
2024-10-24 04:46:01939瀏覽

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

使用 FastAPI 自訂 404 Not Found 頁面

要建立自訂 404 Not Found 頁面,FastAPI 提供了多種方法。合適的方法取決於您的特定要求。

404 狀態碼重新導向

<br>@app.middleware("http") <br>async def redirect_on_not_found(request: Request, call_next):<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

此中間件檢查回應狀態碼並重新導向至自訂頁面,如果程式碼是404。

404 的自訂例外處理程序

<br>@app.exception_handler(404)<br>async def not_found_exception_handler(request : Re>async def not_found_exception_handler(request : Reception, HTTP) :<pre class="brush:php;toolbar:false">return RedirectResponse('https://fastapi.tiangolo.com')

可以專門為404 狀態代碼建立自訂異常處理程序。這樣可以實現更具體、更有針對性的回應。

使用範本自訂錯誤頁面

FastAPI 支援使用範本來呈現自訂錯誤頁面。此範例建立兩個錯誤頁面:

<br>templates = Jinja2Templates(directory='templates')<p>exception_handlers = {</p><pre class="brush:php;toolbar:false">404: not_found_error,
500: internal_error

exception_handlers = {


app = FastAPI(exception_handlers=exception_handlers)模板位於'templates' 目錄中,可以根據您的需求進行自訂。 選擇最適合您的應用程式的方法,您可以在 FastAPI 中建立自訂 404 Not Found 頁面。

以上是如何在 FastAPI 中建立自訂 404 Not Found 頁面?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn