如何在 FastAPI 中进行发布/重定向/获取 (PRG)?



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

你试了什么?

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

它总是显示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")

您也可以在 FastAPI 错误问题中看到此问题

我也遇到了这个问题,这很出乎意料。我猜RedirectResponse继承了HTTP POST动词,而不是成为HTTP GET。在 FastAPI GitHub 存储库中涵盖此问题的问题有一个很好的修复:

开机自检端点

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)

基本重定向 GET 终结点

@router.get('/account')
async def account():
# Implementation details ...

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

有关 302 状态代码的详细信息,请查看 https://httpstatuses.com/302 具体:

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

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

最新更新