带或不带尾部斜杠的 fastapi post 方法调用

问题描述 投票:0回答:2

我试图编写一个 fastapi post 方法:

@app.post('/method/final_path/', tags=['method/final_path'])

当我拨打邮递员电话时 https://....../method/final_path/
我得到了预期的结果,但是如果调用更改为 https://......./method/final_path
我收到 405-method not allowed.

根据 FastAPI 文档,尾部斜杠应该无关紧要,所以理想情况下

@app.post('/method/final_path/', tags=['method/final_path'])
@app.post('/method/final_path', tags=['method/final_path'])

有邮递员电话:

  • https://......./method/final_path/
  • https://......./method/final_path

以上 4 种组合应该给出相同的结果。那我到底做错了什么?

版本:
fastapi-0.63
星光-0.13.6

提前致谢。

python-3.x fastapi starlette
2个回答
7
投票

尝试使用

APIRouter
定义路线,而不是直接使用
app
。默认情况下,
APIRouter
redirect_slashes
设置为
True


0
投票

这已经不是实际问题,但这里有帮助的见解。

FastAPI 发布了具有全局

redirect_slashes
及其默认
True
的功能。它将重定向到您在代码中定义的路由。

  1. 不带斜杠的大小写定义

@app.get("/route_slash_example")

http://127.0.0.1:8000/route_slash_example/
将被重定向至
http://127.0.0.1:8000/route_slash_example

  1. 用斜杠定义大小写

@app.get("/route_slash_example/")

http://127.0.0.1:8000/route_slash_example
将被重定向到
http://127.0.0.1:8000/route_slash_example/

© www.soinside.com 2019 - 2024. All rights reserved.