【问题标题】:FastAPI handling and redirecting 404FastAPI 处理和重定向 404
【发布时间】:2020-11-09 04:42:56
【问题描述】:

如果出现 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 实现这一目标?

【问题讨论】:

    标签: python http-status-code-404 fastapi


    【解决方案1】:

    我们可以通过使用 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)
    

    【讨论】:

      【解决方案2】:

      我用这个方法,

      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文件。

      【讨论】:

        【解决方案3】:

        我知道为时已晚,但这是以您个人方式处理 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 作为参数传递给函数。我在不需要变量的地方使用了___

        【讨论】:

          猜你喜欢
          • 2012-01-06
          • 1970-01-01
          • 2015-11-29
          • 2021-04-14
          • 2022-10-15
          • 2022-07-22
          • 2015-03-20
          • 1970-01-01
          • 2015-04-13
          相关资源
          最近更新 更多