>  기사  >  백엔드 개발  >  FastAPI에서 사용자 정의 404 찾을 수 없음 응답을 처리하는 방법은 무엇입니까?

FastAPI에서 사용자 정의 404 찾을 수 없음 응답을 처리하는 방법은 무엇입니까?

DDD
DDD원래의
2024-10-24 02:06:29910검색

How to Handle Custom 404 Not Found Responses in FastAPI?

FastAPI를 사용하여 사용자 정의 404 찾을 수 없는 페이지를 반환하는 방법

404 응답 상태 코드가 발생하면 기본 오류 페이지는 다음과 같습니다. 일반적으로 웹 애플리케이션에 표시됩니다. 그러나 보다 개인화된 환경을 위해 사용자 정의 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>

예외 처리기 매개변수

또는 다음의 예외 처리기 매개변수를 사용할 수 있습니다. 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>

참고: 이 예에서는 리디렉션이 수행됩니다. 그러나 필요에 따라 사용자 정의 응답, 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 찾을 수 없음 응답을 처리하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.