我有一个简单的 FastAPI 端点,我想在其中接收字符串值。在本例中,我尝试使用 JSON 正文,但基本上不需要是 JSON。我真的只需要一个简单的字符串来将请求彼此分开。不幸的是,我无法使用以下命令访问任何请求参数GET
方法。我也尝试过POST
方法,但我收到错误:
request:
url = "http://127.0.0.1:5000/ping/"
payload=json.dumps({"key":"test"})
headers = {
"Content-Type": "application/json"
}
response = requests.request("POST", url, headers=headers, json=payload)
print(response.text)
api:
@app.get("/ping/{key}")
async def get_trigger(key: Request):
key = key.json()
test = json.loads(key)
print(test)
test2 = await key.json()
print(key)
print(test2)
return
我无法打印任何内容post
or put
:
@app.post("/ping/{key}")
async def get_trigger(key: Request):
...
or
@app.put("/ping/{key}")
async def get_trigger(key: Request):
I get a 405 Method not allowed
error.
我怎样才能解决这个问题?
The 405 Method Not Allowed状态码表明“服务器知道请求方法,但目标资源不支持该方法"。例如,当您尝试发送电子邮件时,您会收到此错误POST
请求给一个GET
路线(如第一个示例所示)。然而,这并不是代码(在客户端和服务器端)的唯一问题。下面给出了一个示例,说明如何使用以下方法实现您在问题中所描述的内容Path参数。使用同样的方法也可以实现Query参数, 也Request Body。请看一下Python 请求文档关于如何为每种情况指定参数/主体。我也强烈建议采取FastAPI教程在线——您可以在那里找到您正在寻找的大部分答案。
app.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/ping/{ping_id}")
async def get_trigger(ping_id: str):
return {"ping_id": ping_id}
test.py
import requests
url = 'http://127.0.0.1:8000/ping/test1'
resp = requests.get(url=url)
print(resp.json())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)