FastAPI处理和重定向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 实现这一目标?


江户川乱折腾
浏览 824回答 3
3回答

HUX布斯

我们可以通过使用 FastAPI 的exception_handler来实现:如果你赶时间,你可以使用这个:from fastapi.responses import RedirectResponsefrom 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)

FFIVE

我知道为时已晚,但这是以您个人的方式处理 404 异常的最短方法。重定向from fastapi.responses import RedirectResponse@app.exception_handler(404)async def custom_404_handler(_, __):&nbsp; &nbsp; return RedirectResponse("/")自定义神社模板from fastapi.templating import Jinja2Templatesfrom fastapi.staticfiles import StaticFilestemplates = Jinja2Templates(directory="templates")app.mount("/static", StaticFiles(directory="static"), name="static")@app.exception_handler(404)async def custom_404_handler(request, __):&nbsp; &nbsp; return templates.TemplateResponse("404.html", {"request": request})从文件提供 HTML@app.exception_handler(404)async def custom_404_handler(_, __):&nbsp; &nbsp; return FileResponse('./path/to/404.html')直接提供 HTMLfrom fastapi.responses import HTMLResponseresponse_404 = """<!DOCTYPE html><html><head>&nbsp; &nbsp; <title>Not Found</title></head><body>&nbsp; &nbsp; <p>The file you requested was not found.</p></body></html>"""&nbsp; &nbsp;&nbsp;@app.exception_handler(404)async def custom_404_handler(_, __):&nbsp; &nbsp; return HTMLResponse(response_404)注意:exception_handler装饰器将当前request和exception作为参数传递给函数。我用过_并且__不需要变量。

子衿沉夜

我用这个方法,from fastapi.responses import RedirectResponsefrom starlette.exceptions import HTTPException as StarletteHTTPExceptionapp.mount("/static", StaticFiles(directory="static"), name="static")templates = Jinja2Templates(directory="templates")@app.exception_handler(StarletteHTTPException)async def custom_http_exception_handler(request, exc):&nbsp; &nbsp; return templates.TemplateResponse("404.html", {"request": request})确保你有静态文件夹,用于静态文件和模板文件夹,用于 html 文件。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python