【问题标题】:Can't access or print any request data with FastAPI无法使用 FastAPI 访问或打印任何请求数据
【发布时间】:2022-10-08 16:30:53
【问题描述】:

我有一个简单的 FastAPI 端点,我想在其中接收一个字符串值。在这种情况下,我尝试使用 JSON 正文,但基本上它不需要是 JSON。我真的只需要一个简单的字符串来将请求彼此分开。不幸的是,我无法使用GET 方法访问任何请求参数。我也尝试了POST 方法,但出现错误:

要求:

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)

接口:

@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 

我无法使用postput 打印任何内容:

@app.post("/ping/{key}")
async def get_trigger(key: Request):
...
   or

@app.put("/ping/{key}")
async def get_trigger(key: Request):

我收到405 Method not allowed 错误。

我怎样才能解决这个问题?

【问题讨论】:

    标签: python api fastapi


    【解决方案1】:

    405 Method Not Allowed 状态码表示“服务器知道请求方法,但目标资源不支持这种方法".例如,当您尝试将 POST 请求发送到 GET 路由(如您的第一个示例中所示)时,您会收到此错误。但是,这不是您的代码(在客户端和服务器端)的唯一问题。下面给出了一个示例,说明如何使用Path parameters 实现您在问题中描述的内容。使用Query parametersRequest Body 也可以达到同样的效果。请查看Python requests documentation,了解如何为每种情况指定参数/正文。我还强烈建议在线使用FastAPI tutorial——您会在那里找到您正在寻找的大部分答案。

    应用程序.py

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/ping/{ping_id}")
    async def get_trigger(ping_id: str):
        return {"ping_id": ping_id}
    

    测试.py

    import requests
    
    url = 'http://127.0.0.1:8000/ping/test1'
    resp = requests.get(url=url) 
    print(resp.json())
    

    【讨论】:

    • 我收到了404 not found 与您的解决方案
    • 是的,我在浏览器中尝试过。这是 fastapi 终端输出:INFO: 127.0.0.1:64153 - "GET /ping/test1 HTTP/1.1" 404 Not Found。我在端口 5000 顺便说一句
    • 我知道。如果我使用错误的端口,我不会看到 fastapi 打印信息。我复制/粘贴了您的代码,但是通过使用uvicorn main:app --reload 启动服务器,如文档中所述,我得到ERROR: Error loading ASGI app. Could not import module "main".。我的文件名为 main.py
    • 顺便说一句,我需要在后端阅读/打印ping_id,而不是在客户端。您的解决方案中的打印语句位于客户端。
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 2023-01-08
    • 2016-11-18
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多