我是一个瑞克滚动网站,因为不和,我想重定向到瑞克滚动页面上的404响应状态代码。
我试过以下几种方法,但没有奏效:
@app.exception_handler(fastapi.HTTPException)
async def http_exception_handler(request, exc):
...发布于 2022-04-08 16:33:30
更新
更优雅的解决方案是使用自定义异常处理程序,传递要处理的异常的状态代码,如下所示:
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://fastapi.tiangolo.com')或者,使用exception_handlers类的FastAPI参数如下所示:
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)注意:当OP要求重定向用户时,返回RedirectResponse上面的。但是,您可以返回一些自定义的Response、HTMLResponse或Jinja2 TemplateResponse,如下面的示例所示。
工作实例:
app.py
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.exceptions import HTTPException
async def not_found_error(request: Request, exc: HTTPException):
return templates.TemplateResponse('404.html', {'request': request}, status_code=404)
async def internal_error(request: Request, exc: HTTPException):
return templates.TemplateResponse('500.html', {'request': request}, status_code=500)
templates = Jinja2Templates(directory='templates')
exception_handlers = {
404: not_found_error,
500: internal_error
}
app = FastAPI(exception_handlers=exception_handlers)templates/404.html
<!DOCTYPE html>
<html>
<title>Not Found</title>
<body>
<h1>Not Found</h1>
<p>The requested resource was not found on this server.</p>
</body>
</html>templates/500.html
<!DOCTYPE html>
<html>
<title>Internal Server Error</title>
<body>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error or
misconfiguration and was unable to complete your request.
</p>
</body>
</html>原始答案
您需要创建一个middleware并检查response的status_code。如果是404,则返回一个RedirectResponse。示例:
from fastapi import Request
from fastapi.responses import RedirectResponse
@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发布于 2022-04-10 17:13:30
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException
# --- Constants --- #
templates = Jinja2Templates(directory="./templates")
# --- Error handler --- #
def lost_page(request, exception):
headers = {"Content-Type": "text/html"}
if isinstance(exception, HTTPException):
status_code = exception.status_code
detail = exception.detail
elif isinstance(exception, Exception):
status_code = 500
detail = "Server Error"
headers["X-Error-Message"] = exception.__class__.__name__
headers["X-Error-Line"] = str(exception.__traceback__.tb_lineno)
else:
status_code = 500
detail = f"Server Error\n\nDetails: {exception}"
return templates.TemplateResponse(
"404.html",
{"request": request, "status_code": status_code, "detail": detail},
status_code=status_code,
headers=headers,
)
exception_handlers = {num: lost_page for num in range(400, 599)}
app = FastAPI(exception_handlers=exception_handlers)这是我在几个项目中使用的一个片段,它本质上是对所有400和500个状态代码的一个捕捉。
from fastapi import FastAPI
from fastapi.templating import Jinja2Templates
from starlette.exceptions import HTTPException
# --- Constants --- #
templates = Jinja2Templates(directory="./templates")这个块导入相关的库并初始化Jinja2Templates,这允许我们使用FastAPI呈现HTML。文档。
我们来解剖一下
def lost_page(request, exception):
headers = {"Content-Type": "text/html"}
if isinstance(exception, HTTPException):
status_code = exception.status_code
detail = exception.detail
elif isinstance(exception, Exception):
status_code = 500
detail = "Server Error"
headers["X-Error-Message"] = exception.__class__.__name__
headers["X-Error-Line"] = str(exception.__traceback__.tb_lineno)
else:
status_code = 500
detail = f"Server Error\n\nDetails: {exception}"
return templates.TemplateResponse(
"404.html",
{"request": request, "status_code": status_code, "detail": detail},
status_code=status_code,
headers=headers,
)FastAPI的异常处理程序提供两个参数,一个是导致异常的请求对象,另一个是引发的异常。
def lost_page(request, exception):^^我们的函数接受这两个参数。
headers = {"Content-Type": "text/html"}这些是我们将与请求一起发送回的头。
if isinstance(exception, HTTPException):
status_code = exception.status_code
detail = exception.detail
elif isinstance(exception, Exception):
status_code = 500
detail = "Server Error"
headers["X-Error-Name"] = exception.__class__.__name__
else:
status_code = 500
detail = f"Server Error\n\nDetails: {exception}"如果exception参数是一个HTTPException (由Starlette/FastAPI引发),那么我们将适当地设置status_code和detail。HTTPException的一个例子是404错误,如果您尝试访问不存在的端点,HTTPException将由FastAPI自动引发和处理。
然后,我们检查它是否是Exception的实例,这是Python内置的异常类之一。这包括一些异常,如ZeroDivisionError、FileNotFoundError等。这通常意味着这是代码中的一个问题,例如试图打开一个不存在的文件,除以零,使用未知的属性,或者引发在端点函数中没有处理的异常。
else块在任何情况下都不应该触发,而且可以删除,这只是为了安抚我的良心。
设置status_code、detail和headers后,
return templates.TemplateResponse(
"404.html",
{"request": request, "status_code": status_code, "detail": detail},
status_code=status_code,
headers=headers,
)我们返回404个模板,TemplateResponse函数接受几个参数,"404.html"是我们想要返回的文件,{"request": request, "status_code": status_code, "detail": detail}是请求对象,以及我们想要填充的嵌入值(嵌入是在jinja2和jinja2之间传递信息的一种方式)。然后,我们定义响应的状态代码及其标题。
这是我在错误处理程序旁边使用的404html模板。
exception_handlers = {num: lost_page for num in range(400, 599)}
app = FastAPI(exception_handlers=exception_handlers)异常处理程序使用dict解译来创建状态代码字典,以及应该调用的函数,
exception_handlers = {400: lost_page, 401: lost_page, 402: lost_page, ...}它将如何处理理解,直到599。
FastAPI允许我们将这个dict作为FastAPI类的参数传递,
app = FastAPI(exception_handlers=exception_handlers)这告诉FastAPI在端点函数返回特定状态代码时运行以下函数。
总之,上面的代码片段和这错误模板应该可以帮助您以一种良好、用户友好和干净的方式处理所有FastAPI错误。
https://stackoverflow.com/questions/71800133
复制相似问题