FastAPI 重定向给出方法不允许错误

use*_*177 3 python http starlette fastapi

我创建了一个登录路径,在其中发布表单数据并设置 cookie。设置 cookie 后,我重定向到“/main”,在那里我得到{detail:"Method Not Allowed"}响应。

@app.post("/login")
async def login(request:Request):
     response = RedirectResponse(url="/main")
     response.set_cookie(key="cookie",value="key-value")
     return response

@app.get("/main")
async def root(request:Request, cookie: Optional[str] = Cookie(None)):
     if cookie:
        answer = "set to %s" % cookie
     else:
          answer = "not set"

     return {"value": answer}
Run Code Online (Sandbox Code Playgroud)

我进一步检查了控制台,发现在重定向期间向“/main”发出了 POST 请求,从而导致了错误。当我将其更改为app.post("/main")它时,效果很好。我该如何避免这个错误?我不想每次都发出访问“/main”的发布请求。提前致谢。

use*_*177 8

我发现在 FastAPI 中,starlette 响应默认具有代码 307,它在重定向期间保留该方法,因此保留了 post 请求。response.status_code = 302我通过在返回响应之前添加来解决这个问题。