如何根据表单输入更新现有的Python Flask网页?

时间:2016-07-28 16:04:02

标签: python html forms flask

我正在尝试使用Flask构建预测Web应用程序。应用程序应该接受用户输入,通过python训练模型处理它,然后将结果显示为输入表单旁边的图表。

我的代码如下所示:

HTML表格:

<form class = "prediction-options" method = "post" action = "/prediction/results">
  <!--the input fields-->
</form>

Flask app.py

@app.route("/")
def main():
    return render_template('index.html')    

@app.route("/prediction/results", methods = ['POST'])
def predict():
    input_aqi = float(request.form['aqi'])/272
    input_pm2_5 = float(request.form['pm2_5'])/224
    input_pm10 = float(request.form['pm10'])/283
    input_so2 = float(request.form['so2'])/36
    input_no2 = float(request.form['no2'])/110
    input_co = float(request.form['co'])/1.83
    input_o3 = float(request.form['o3'])/124
    input_list = [[input_aqi,input_pm2_5,input_pm10,input_so2,input_no2,input_co,input_o3]]


    output_acute_bronchitis = model_acute_bronchitis.predict(input_list)
    output_asthma = model_asthma.predict(input_list)
    output_asthmatic_bronchitis = model_asthmatic_bronchitis.predict(input_list)
    output_aurti = model_aurti.predict(input_list)
    output_bronchitis = model_bronchitis.predict(input_list)
    output_pneumonia = model_pneumonia.predict(input_list)

    d = collections.OrderedDict()
    d['acute_bronchitis'] = output_acute_bronchitis[0]
    d['asthma'] = output_asthma[0]
    d['asthmatic_bronchitis'] = output_asthmatic_bronchitis[0]
    d['aurti'] = output_aurti[0]
    d['bronchitis'] = output_bronchitis[0]
    d['pneumonia'] = output_pneumonia[0]

    prediction = jsonify(d)
    return prediction

现在,我已设法接收用户输入并在'/ prediction / results'页面上呈现预测结果。如何将结果显示在“/”页面上?我试着这样做:

@app.route("/", methods = ['POST','GET'])
def main():
    if request.method == 'POST':
        def predict():
           #predict function that returns prediction
    return render_template('index.html')

但我总是收到socket.error: [Errno 32] Broken pipe错误消息。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可以使用session,在predict路线的最后一行之前,使用

存储预测
session['prediction'] = prediction

然后您可以访问应用程序中的任何其他路径,例如,您可以将其设置为/

@app.route("/", methods = ['POST','GET'])
def main():
    if request.method == 'POST':
        pass

    prediction = session['prediction']

    return render_template('index.html', prediction=prediction)