如何使用Flask应用结合HTML实现预测结果在同一页面展示
解决方案
一、修改Flask后端代码
核心修改逻辑:POST请求完成预测后不要直接返回纯文本,而是将预测结果作为参数传入模板渲染,保持在原页面展示,同时修复原有代码的参数类型问题。
import numpy as np from flask import Flask, request, render_template import pickle app = Flask(__name__) # 加载预训练模型 with open('model.pkl','rb') as pkl_file: model = pickle.load(pkl_file) index_dict = pickle.load(pkl_file) @app.route('/') def home(): # 直接返回预测页面,无需用户手动跳转路径 return render_template('index.html') @app.route('/predict',methods=['GET','POST']) def predict(): price = None if request.method=='POST': result = request.form area_type = result.get("area_type") # 区域类型编码 if area_type == 'Super built-up Area': area_type =0 elif area_type == 'Plot Area': area_type = 1 elif area_type == 'Built-up Area': area_type = 2 else: area_type = 3 # 构造预测输入,注意将表单字符串转为数值类型 predict_list =np.zeros(134) predict_list[0] = area_type predict_list[1] = int(result["bedroom"]) predict_list[2] = float(result["sqft"]) predict_list[3] = int(result["bathroom"]) predict_list[4] = int(result["year"]) # 计算预测价格 predicted_price = round(model.predict([predict_list])[0],2) price = f"您的房屋预估价格为 ₹{predicted_price} lakhs" # 无论GET还是POST请求都返回原页面,POST时带入预测结果 return render_template('index.html', price=price) if __name__ == "__main__": app.run(debug=True)
二、修改前端index.html代码
核心修改逻辑:表单提交到当前路径,优化结果展示逻辑,修复原有HTML语法问题。
<body> <div class="container"> <div class="title">Predict Here</div> <div class="content"> <!-- 表单action置空,默认提交到当前页面路径 --> <form method="post"> <div class="user-details"> <div class="input-box"> <span class="area_type">Area Type</span> <select name="area_type" id=area_type><br><br> <option value= "Select">Select</option> <option value= "Plot Area">Plot Area</option> <option value= "Super built-up Area">Super built-up Area</option> <option value= "Built-up Area">Built-up Area</option> </select><br> </div> <div class="input-box"> <span class="details">Total Sqft</span> <input type="text" placeholder="Enter the Total_sqrft" name="sqft" required> </div> <div class="input-box"> <span class="details">Bedrooms</span> <input type="number" placeholder="Enter no. of Bedrooms" min="1" name="bedroom" > </div> <div class="input-box"> <span class="details">Bathrooms</span> <input type="number" placeholder="Enter no. of Bathrooms" min="1" name="bathroom" > </div> <div class="input-box"> <span class="details">Year</span> <input type="text" placeholder="Enter the Year" maxlength="4" name="year" required> </div> </div> </div> <div class="button"> <input type="submit" value="Predict"> </div> <!-- 仅当有预测结果时展示 --> {% if price %} <p>{{ price }}</p> {% endif %} </form> </div> </div> </body>
可选优化:无刷新提交
如果需要页面不刷新就展示预测结果,可以使用原生JS或者jQuery发送Ajax请求提交表单,拿到返回结果后直接插入到页面的结果位置即可。
内容的提问来源于stack exchange,提问作者sravya chebolu
相关产品推荐
相关产品推荐

