」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在FastAPI中建立自訂404頁面?

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

發佈於2024-11-26
瀏覽:138

How to Create a Custom 404 Page in FastAPI?

如何使用 FastAPI 返回自訂 404 Not Found 頁面?

簡介

在建立 Web 應用程式時,這是必不可少的適當地處理 HTTP 狀態碼。您可能遇到的常見狀態代碼是 404 Not Found,這表示無法找到所要求的資源。本文將探討使用 FastAPI(一種用於建立 Web API 的現代 Python 框架)傳回自訂 404 頁面的各種方法。

異常處理方法

FastAPI 提供了一種便捷的方法透過其異常處理機制來處理異常。您可以定義自訂處理程序來處理 404 例外狀況並傳回自訂回應。

@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc: HTTPException):
    return RedirectResponse('https://fastapi.tiangolo.com')

或者,您可以使用FastAPI類別的exception_handlers參數來註冊全域異常處理程序。

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

exception_handlers = {404: not_found_error}
app = FastAPI(exception_handlers=exception_handlers)

中間件方法

另一種方法是建立一個中間件來攔截 HTTP 回應並檢查狀態碼。如果狀態碼為404,則中間件可以在回應到達用戶端之前傳回自訂回應。

@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

自訂頁面回應

使用上面提到的方法,您可以傳回一個簡單的重新導向回應。但是,您也可以透過定義模板並傳回 TemplateResponse 來建立更自訂的 404 頁面。

from fastapi.templating import Jinja2Templates

templates = Jinja2Templates(directory='templates')

async def not_found_error(request: Request, exc: HTTPException):
    return templates.TemplateResponse('404.html', {'request': request}, status_code=404)

在templates 目錄中,建立一個404.html 模板,其中包含自訂404 頁面所需的內容。

結論

透過利用例外處理程序、中介軟體或自訂頁面回應,您可以在 FastAPI 中輕鬆實現自訂 404 Not Found 頁面。這使您能夠在找不到所要求的資源時提供更用戶友好的體驗,從而增強 Web 應用程式的整體用戶體驗。

版本聲明 本文轉載於:1729691392如有侵犯,請洽[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3