烧瓶无法从邮递员或网页上获取帖子数据,但可以在python请求中工作

时间:2017-07-29 04:14:17

标签: python flask

我使用flask作为API服务器。 我用python测试它没关系!

class ModelLoader(MethodView):
    def __init__(self):
        pass

    def post(self):
        content = request.get_json()
        request
        X_input = content['X_input']
        X_in = str(X_input)
        pred_val,posib = predictor.predict(X_input=X_in)
        pred_val = pred_val.tolist()
        posib = str(round(posib,4)*100)
        #posib = posib.tolist()
        return jsonify({'pred_val': pred_val,'confident':posib})

    def initialize_models(json_path, weights_path, normalized_x, normalized_y):
        global predictor
        predictor = Predictor(json_path, weights_path, normalized_x, normalized_y)
        predictor.compile_model(loss='categorical_crossentropy', optimizer='adam')


    def run(host='0.0.0.0', port=19865):
        """Run a WSGI server using gevent."""
        app.add_url_rule('/predict', 
        view_func=ModelLoader.as_view('predict'))
        print('running server http://{0}'.format(host + ':' + str(port)))
        WSGIServer((host, port), app).serve_forever()

测试代码

import requests
def get_predictions(X_input):
    """Get predictions from a rest backend for your input."""
    print("Requesting prediction for XOR with {0}".format(X_input))
    r = requests.post("http://yansheng.wang:19865/predict", json={'input':  X_input})
print(r.status_code, r.reason)
resp = r.json()
prediction = resp['pred_val']
confident = resp['confident']
print("XOR of input: {0} is {1},on confident of {2} ".format(X_input, prediction,confident))

if __name__ == '__main__':

    X_inputs = ["885863343916543724"]

    for x_input in X_inputs:
        get_predictions(x_input)

当我运行它时,我无法从邮递员或网页发布数据!

服务器控制台的输出差异如下,出了什么问题?:

45.76.182.34 - - [2017-07-29 12:11:55] "POST /predict HTTP/1.1" 200 162 0.044396
45.76.182.34 - - [2017-07-29 12:12:03] "POST /predict?input=3423432432424233 HTTP/1.1" 400 303 0.001046

1 个答案:

答案 0 :(得分:0)

当您使用测试代码测试代码时,您将在json正文中传递X_input值。

# part of request
json={'input':  X_input}

# I would suggest make the key consistent

# inside post menthod
content = request.get_json()
request
X_input = content['X_input']
X_in = str(X_input)

但是当你从网络/邮递员发送它时,你会用url params发送它。

"POST /predict?input=3423432432424233 HTTP/1.1" 400

因此它失败了。从json体内的邮递员发送此数据。它应该工作。

示例:

postman post call example with json body