ホームページ  >  記事  >  バックエンド開発  >  FastAPI でカスタム 404 Not Found 応答を処理する方法は?

FastAPI でカスタム 404 Not Found 応答を処理する方法は?

DDD
DDDオリジナル
2024-10-24 02:06:29910ブラウズ

How to Handle Custom 404 Not Found Responses in FastAPI?

FastAPI を使用してカスタム 404 Not Found ページを返す方法?

404 応答ステータス コードが発生した場合、デフォルトのエラー ページは次のとおりです。通常、Web アプリケーションで表示されます。ただし、よりパーソナライズされたエクスペリエンスを実現するために、カスタム 404 ページを提供することもできます。 FastAPI を使用すると、カスタム 404 ページの実装は簡単です。

カスタム例外ハンドラー

効果的な方法は、カスタム例外ハンドラーを利用することです。処理したいステータス コードを指定することで、対象のハンドラーを作成できます。

<code class="python">from fastapi.responses import RedirectResponse
from fastapi.exceptions import HTTPException

@app.exception_handler(404)
async def not_found_exception_handler(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/404')</code>

Exception Handlers パラメーター

または、次の例外ハンドラー パラメーターを使用することもできます。 FastAPI クラス。

<code class="python">from fastapi import FastAPI, Request

def not_found_error(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/404')

exception_handlers = {404: not_found_error}
app = FastAPI(exception_handlers=exception_handlers)</code>

注: これらの例では、リダイレクトが実行されます。ただし、必要に応じてカスタム Response、HTMLResponse、または Jinja2 TemplateResponse を返すことができます。

実際の例

次の例を考えてみましょう:

app.py

<code class="python">from fastapi.responses import RedirectResponse
from fastapi.exceptions import HTTPException
from fastapi import Request

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

async def internal_error(request: Request, exc: HTTPException):
    return RedirectResponse('https://example.com/500')

exception_handlers = {404: not_found_error, 500: internal_error}
app = FastAPI(exception_handlers=exception_handlers)</code>

404.html テンプレート

<code class="html"><!DOCTYPE html>
<html>
<title>404 Not Found</title>
<body>
<h1>Not Found</h1>
<p>The requested resource could not be found.</p>
</body>
</html></code>

500.html テンプレート

<code class="html"><!DOCTYPE html>
<html>
<title>500 Internal Server Error</title>
<body>
<h1>Internal Server Error</h1>
<p>An internal error has occurred. Please try again later.</p>
</body>
</html></code>

以上がFastAPI でカスタム 404 Not Found 応答を処理する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。