FastAPI 处理和重定向 404

Yag*_*nci 14 python http-status-code-404 fastapi

如果出现 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'))
Run Code Online (Sandbox Code Playgroud)

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

from django.shortcuts import redirect

def view_404(request, exception=None):
    return redirect('/')
Run Code Online (Sandbox Code Playgroud)

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

Shi*_*kar 17

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

重定向

from fastapi.responses import RedirectResponse


@app.exception_handler(404)
async def custom_404_handler(_, __):
    return RedirectResponse("/")
Run Code Online (Sandbox Code Playgroud)

自定义 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})
Run Code Online (Sandbox Code Playgroud)

从文件提供 HTML

@app.exception_handler(404)
async def custom_404_handler(_, __):
    return FileResponse('./path/to/404.html')
Run Code Online (Sandbox Code Playgroud)

直接提供 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)
Run Code Online (Sandbox Code Playgroud)

注意exception_handler装饰器将当前的requestexception作为参数传递给函数。我已经使用了_and__不需要变量的地方。


Yag*_*nci 9

我们可以通过使用 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("/")
Run Code Online (Sandbox Code Playgroud)

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

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


app.add_exception_handler(UberSuperHandler, function_for_uber_super_handler)
Run Code Online (Sandbox Code Playgroud)