发布请求返回空的正文响应(无200)python

时间:2020-09-15 17:03:59

标签: json flask python-requests

发送对机器学习API的响应后返回空主体, 请求的代码很简单:

import json
import requests
for row in new_f.itertuples():
            features = [{
                       'CRIM' : str(row.CRIM), 
                       'ZN' : str(row.ZN), 
                       'INDUS' : str(row.INDUS), 
                       'CHAS' : str(row.CHAS), 
                       'NOX' : str(row.NOX), 
                       'RM' : str(row.RM), 
                       'AGE' : str(row.AGE), 
                       'DIS' : str(row.DIS), 
                       'RAD' : str(row.RAD), 
                       'TAX' : str(row.TAX), 
                       'PTRATIO' : str(row.PTRATIO), 
                       'B' : str(row.B), 
                       'LSTAT' : str(row.LSTAT)
                       }]
            postre = json.dumps(features)
            print(postre)
            response  = requests.post(url = 'http://127.0.0.1:5000/predict' , data= postre )
            print(response.json())

print(postre)的输出是:

[{"CRIM": "0.00632", "ZN": "18.0", "INDUS": "2.31", "CHAS": "0", "NOX": "0.538", "RM": "6.575", "AGE": "65.2", "DIS": "4.09", "RAD": "1", "TAX": "296.0", "PTRATIO": "15.3", "B": "396.9", "LSTAT": "4.98"}]

在打印response.json时出现错误:

第34行,位于\ n query_ = pd.get_dummies(pd.DataFrame(json _))..... ValueError:无对象可连接\ n'}

这是Post api方法的代码段:

if flask.request.method == 'POST':
        try:
            json_ =request.json
            print(json_)
            query_ =pd.get_dummies(pd.DataFrame(json_))
            query = query_.reindex(columns = model_columns, fill_value = 0)
            prediction = list(classifier.predict(query))

            return jsonify({
                "prediction":str(prediction)
            })
        except:
            return jsonify({
                "trace": traceback.format_exc()
            })

邮递员请求应用程序返回所需结果:


{
    "prediction": "[42.267999999999994]"
}

2 个答案:

答案 0 :(得分:0)

您是否从Flask导入了请求?

json_ = flask.request.json

代替json_ = request.json

答案 1 :(得分:0)

首先,您可以在请求中发送列表,而无需序列化。并且,如果将其作为json发送,它将把标头中的Content-Type更改为application/json。因此,使用:

response = requests.post(url = 'http://127.0.0.1:5000/predict', json=features)

然后,您可以查看响应是什么,

print(request.get_json())
print(request.json)

如果您使用:

get_json(force=True), it will try to parse it as JSON even if you send with wrong mimetype.