简体   繁体   English

Flask API 适用于 GET 但不适用于 POST 方法(heroku)

[英]Flask API works for GET but not for POST methods (heroku)

I run a very spartan app for machine learning inference that's structured as such:我为机器学习推理运行了一个非常简陋的应用程序,其结构如下:

app.py:应用程序.py:

from flask import Flask, request, jsonify
import pandas as pd
from joblib import load

app = Flask(__name__)

@app.route('/predict', methods=['POST'])
def predict():
    df = pd.DataFrame(request.json)
    df = df.reindex(columns=feature_columns, fill_value=0)
    prediction = list(ada.predict(df))
    return jsonify({"prediction": int(prediction[0])})

@app.route('/test', methods=['GET'])
def test():
    return "get successful"

if __name__ == '__main__':
    ada = load("./model/adaboost_model")
    feature_columns = load("./model/feature_columns")
    app.run()

The requirements.txt : requirements.txt

Flask
gunicorn
pandas
joblib

Procfile :档案

web: gunicorn -b:$PORT app:app

and a Model/ folder which contains the two pickled Adaboost models.和一个 Model/ 文件夹,其中包含两个腌制的 Adaboost 模型。

I deployed this on Heroku, the GET on /test endpoint works fine, the app works fine, returns 404 for random requests, and recognizes that /predict only has a POST method.我将它部署在 Heroku 上,/test 端点上的 GET 工作正常,应用程序工作正常,随机请求返回 404,并识别 /predict 只有一个 POST 方法。 However when I run POST I get an Internal Server error, I'm sure it's not the actual code of the POST method that's causing problems, because a simple POST method I wrote for testing also fails and it doesn't do anything code related.但是,当我运行 POST 时,我得到一个内部服务器错误,我确定这不是导致问题的 POST 方法的实际代码,因为我为测试编写的一个简单的 POST 方法也失败了,它没有做任何与代码相关的事情。

Locally this runs perfectly fine, tested with Postman, the inference is correct and all.在本地,这运行得非常好,用 Postman 测试,推断是正确的。 What could be going wrong with the POST requests when deployed on Heroku?在 Heroku 上部署时,POST 请求可能会出现什么问题?

So the problem seems to be with gunicorn and the code that runs before app.run() , transferring the loading of the model and feature columns into the actual POST predict() method works perfectly now.所以问题似乎出在 gunicorn 和app.run()之前运行的代码,将 model 和特征列的加载转移到实际的 POST predict()方法现在可以完美运行。

However this isn't optimal, because every time a POST request is made you need to load the model again, but it works and isn't so bad because I will only use this POST method once every hour or so.然而这并不是最优的,因为每次发出 POST 请求时,您都需要再次加载 model,但它可以工作并且还不错,因为我只会每隔一小时左右使用一次这种 POST 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM