RuntimeError:在请求上下文之外工作(Flask)

时间:2020-04-18 11:33:40

标签: python flask

@app.route('/predict', methods=['POST'])
def predict():
    message = request.get_json(force=True)
    encoded = message['image']
    decoded = base64.b64decode(encoded)
    image = Image.open(io.BytesIO(decoded))
    processed_image = preprocess_image(image, target_size=(224, 224))
    prediction = model.predict(processed_image)

    test_image_probs = {prediction[0][0] * 100 : "Cat" ,
                        prediction[0][1] * 100 : "Dog"}

    test_image_probs = {v: k for k, v in sorted(test_image_probs.items(), reverse=True)}

    testimage_prob_sorted_keys = list(test_image_probs.keys())
    testimage_prob_sorted_values = list(test_image_probs.values())

    prob_key_1 = testimage_prob_sorted_keys[0]
    prob_value_1 = round(testimage_prob_sorted_values[0], 2)

    prob_key_2 = testimage_prob_sorted_keys[1]
    prob_value_2 = round(testimage_prob_sorted_values[1], 2)

    response = {
        'prediction' : {    
            'prob_key_1' : prob_key_1,
            'prob_value_1' : prob_value_1,
            'prob_key_2' : prob_key_2,
            'prob_value_2' : prob_value_2
            }
        }

    return jsonify(response), prediction

如何传递返回值(预测)以在另一个函数中使用?

我尝试过这个:

prediction = predict()
prediction = prediction[1]

def abc():
    global prediction
    a = prediction[0][0]
    return a

a = abc()
print(a)

和获取错误: RuntimeError:在请求上下文之外工作。

这通常意味着您尝试使用所需的功能 活动的HTTP请求。查阅有关测试的文档 有关如何避免此问题的信息。

0 个答案:

没有答案