使用 python 向 Flask restAPI 发送 Post 请求给出响应错误 500

时间:2021-03-23 03:00:17

标签: python api rest flask

在 ubuntu 18.04 上使用 Flask=1.1.1

我已经构建了一个为机器学习模型提供服务的 restAPI。运行代码后,我使用 Postman 进行了测试,并且运行良好。我想在 python 中复制这种行为,因为我想通过按顺序发送多个请求来进行压力测试。

运行 Flask 应用后,它托管在 http://127.0.0.1:5000/predict

使用 Python 请求模块,我发送了如下的 post 请求(在托管服务器的同一台机器上使用 jupyter notebook):

data = {"A":123, "B":22, etc...}
url_path = 'http://127.0.0.1:5000/predict'
response = requests.post(url_path, json.dumps(data))
response

>>> <Response [500]>

编辑:发送数据不带 json.dumps() 输出相同的响应[500]

我的烧瓶应用的预测看起来像这样:

@app.route("/predict", methods=["POST"])
def predict():
    data = request.get_json()
    print(data)

打印数据(我发送的)显示为 None

我尝试搜索如何使用 python 测试 restAPI,但没有找到它。我是 restAPI 的新手,不确定搜索词,如果这似乎是有用资源的明显链接,将不胜感激。提前致谢!

1 个答案:

答案 0 :(得分:2)

您好像忘记在 predict 方法中添加 request 参数

import json

@app.route("/predict", methods=["POST"])
def predict():
    data = json.loads(request.get_data())
    print(data)

说明:

在您的客户端代码中,您不是在发送 json,而是在发送数据。我无法很好地解释差异,但为了接收 json 并在 request.get_json() 中包含内容,您必须将您的客户端更新为:

data = {"A":123, "B":22, etc...}
url_path = 'http://127.0.0.1:5000/predict'
response = requests.post(url_path, json=json.dumps(data))

This post 将向您提供有关发生情况的更多详细信息