如何在 FastAPI 中执行 Post/Redirect/Get (PRG)?

mrx*_*mrx 7 http-method fastapi

我正在尝试从 POST 重定向到 GET。如何在 FastAPI 中实现这一点?

你尝试了什么?

我已经按照问题#863#FastAPI 的建议尝试了以下 HTTP_302_FOUND、HTTP_303_SEE_OTHER:但没有任何效果!

它总是显示 INFO: "GET / HTTP/1.1" 405 Method Not Allowed

from fastapi import FastAPI
from starlette.responses import RedirectResponse
import os
from starlette.status import HTTP_302_FOUND,HTTP_303_SEE_OTHER

app = FastAPI()

@app.post("/")
async def login():
     # HTTP_302_FOUND,HTTP_303_SEE_OTHER : None is working:(
     return RedirectResponse(url="/ressource/1",status_code=HTTP_303_SEE_OTHER)


@app.get("/ressource/{r_id}")
async def get_ressource(r_id:str):
     return {"r_id": r_id}

 # tes is the filename(tes.py) and app is the FastAPI instance
if __name__ == '__main__':
    os.system("uvicorn tes:app --host 0.0.0.0 --port 80")
Run Code Online (Sandbox Code Playgroud)

您还可以在 FastAPI BUGS 问题中看到此问题

Mic*_*edy 9

我也遇到了这个,这是非常出乎意料的。我猜它RedirectResponse继承了 HTTP POST 动词而不是成为 HTTP GET。FastAPI GitHub repo 上的问题有一个很好的修复:

POST 端点

import starlette.status as status

@router.post('/account/register')
async def register_post():
    # Implementation details ...

    return fastapi.responses.RedirectResponse(
        '/account', 
        status_code=status.HTTP_302_FOUND)
Run Code Online (Sandbox Code Playgroud)

基本重定向 GET 端点

@router.get('/account')
async def account():
    # Implementation details ...
Run Code Online (Sandbox Code Playgroud)

这里重要且不明显的方面是设置status_code=status.HTTP_302_FOUND

有关 302 状态代码的更多信息,请查看https://httpstatuses.com/302特别是:

注意:由于历史原因,用户代理可能会将请求方法从 POST 更改为 GET 以用于后续请求。如果不希望出现此行为,则可以改用 307 临时重定向状态代码。

在这种情况下,动词变化正是我们想要的。

  • 谢谢谢谢谢谢...在尝试您的 302 代码插入修复之前,我已经为此苦苦挣扎了几个小时,无法找到答案。 (3认同)
  • 这非常有效。您能否添加有关状态代码规范如何将 POST 更改为 GET 的注释?对我来说这看起来像魔法:) (2认同)