3 回答

TA貢獻1876條經驗 獲得超6個贊
我們可以通過使用 FastAPI 的exception_handler來實現(xiàn):
如果你趕時間,你可以使用這個:
from fastapi.responses import RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
return RedirectResponse("/")
但更具體的方法是,您可以創(chuàng)建自己的異常處理程序:
class UberSuperHandler(StarletteHTTPException):
pass
def function_for_uber_super_handler(request, exc):
return RedirectResponse("/")
app.add_exception_handler(UberSuperHandler, function_for_uber_super_handler)

TA貢獻1797條經驗 獲得超6個贊
我知道為時已晚,但這是以您個人的方式處理 404 異常的最短方法。
重定向
from fastapi.responses import RedirectResponse
@app.exception_handler(404)
async def custom_404_handler(_, __):
return RedirectResponse("/")
自定義神社模板
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.exception_handler(404)
async def custom_404_handler(request, __):
return templates.TemplateResponse("404.html", {"request": request})
從文件提供 HTML
@app.exception_handler(404)
async def custom_404_handler(_, __):
return FileResponse('./path/to/404.html')
直接提供 HTML
from fastapi.responses import HTMLResponse
response_404 = """
<!DOCTYPE html>
<html>
<head>
<title>Not Found</title>
</head>
<body>
<p>The file you requested was not found.</p>
</body>
</html>
"""
@app.exception_handler(404)
async def custom_404_handler(_, __):
return HTMLResponse(response_404)
注意:exception_handler裝飾器將當前request和exception作為參數傳遞給函數。我用過_并且__不需要變量。

TA貢獻1828條經驗 獲得超3個贊
我用這個方法,
from fastapi.responses import RedirectResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request, exc):
return templates.TemplateResponse("404.html", {"request": request})
確保你有靜態(tài)文件夾,用于靜態(tài)文件和模板文件夾,用于 html 文件。
添加回答
舉報