小编use*_*177的帖子

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”的发布请求。提前致谢。

python http starlette fastapi

3
推荐指数
1
解决办法
4610
查看次数

标签 统计

fastapi ×1

http ×1

python ×1

starlette ×1