【问题标题】:Sending Post request to Flask restAPI using python give response Error 500 [duplicate]使用python向Flask rest API发送Post请求给出响应错误500 [重复]
【发布时间】:2021-03-23 03:00:17
【问题描述】:

在 ubuntu 18.04 上使用 Flask=1.1.1

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

运行烧瓶应用程序后,它托管在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]>

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

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

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

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

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

【问题讨论】:

  • 您可以尝试发送data 变量而不是使用json.dumps() 吗?所以,response = requests.post(url_path, data).
  • 哦,是的,我已经尝试过了,但是输出相同的错误代码 500
  • 哦,想到别的了:那条路线的末尾有有效的return 声明吗?
  • 是的,它返回return jsonify({"pred":"success", "prediction":prediction})

标签: python api rest flask


【解决方案1】:

您好像忘记在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 将为您提供有关发生情况的更多详细信息

【讨论】:

  • 它在没有它的邮递员中是如何工作的?还添加它输出TypeError: predict() missing 1 required positional argument: 'request'
  • 抱歉回答错误。我对其进行了编辑以使数据在烧瓶中正确可用。还要记住返回 jsonify(), 200 之类的内容以防止异常。
  • 谢谢!您能否解释或提供链接来解释为什么它以前在邮递员中工作但它不起作用?
  • 我更新了。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-16
  • 2019-10-19
  • 2022-11-01
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
相关资源
最近更新 更多