FastAPI处理和重定向404

FastAPI handling and redirecting 404

如果出现 HTTPException,我如何使用 FastAPI 重定向请求?

在 Flask 中我们可以这样实现:

@app.errorhandler(404)
def handle_404(e):
    if request.path.startswith('/api'):
        return render_template('my_api_404.html'), 404
    else:
        return redirect(url_for('index'))

或者在 Django 中我们可以使用 django.shortcuts:

from django.shortcuts import redirect

def view_404(request, exception=None):
    return redirect('/')

我们如何使用 FastAPI 实现这一目标?

我们可以通过使用 FastAPI 的 exception_handler:

来实现

如果你赶时间,可以用这个:

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("/")

但更具体的方法是,您可以创建自己的异常处理程序:

class UberSuperHandler(StarletteHTTPException):
    pass
    
def function_for_uber_super_handler(request, exc):
    return RedirectResponse("/")


app.add_exception_handler(UberSuperHandler, function_for_uber_super_handler)

我用这个方法,

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})
  • 确保您有静态文件夹,用于静态文件和模板文件夹的 html 文件。

我知道为时已晚,但这是以您个人的方式处理 404 异常的最短方法。

重定向

from fastapi.responses import RedirectResponse


@app.exception_handler(404)
async def custom_404_handler(_, __):
    return RedirectResponse("/")

自定义 Jinja 模板

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 lang="en">
<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装饰器将当前的requestexception作为参数传递给函数。我在不需要变量的地方使用了 ___