Flask汽车价格预测应用提交表单触发405 Method Not Allowed错误求助
Flask汽车价格预测应用405错误排查与修复
问题核心原因
提交表单出现405 Method Not Allowed,结合你的代码,主要是代码逻辑错误导致请求处理中断,同时可能存在表单配置不匹配的情况:
- 字符串误用列表方法:
company = request.form.get('company')获取的是字符串类型,你却调用了列表的insert方法,直接触发AttributeError,中断请求处理。 - 数据维度不匹配:构建预测DataFrame时,传入了6个元素,但指定列数为5个,
reshape(1,5)因元素数量不符失败,抛出异常。 - GET请求未处理:
/predict路由声明支持GET和POST,但GET请求访问时无响应返回,可能触发非预期状态码。 - 表单配置问题:需确保HTML表单的
action="/predict"且method="POST",否则会因请求方法/路径不匹配触发405。
修正后的代码
from flask import Flask, render_template, request, redirect import pandas as pd import numpy as np import pickle as pk from os.path import dirname, join current_dir = dirname(__file__) file_path = join(current_dir, "./static/Cleaned Car Dataset.csv") app = Flask(__name__) model = pk.load(open('LinearRegression.pkl', 'rb')) car = pd.read_csv(file_path) @app.route('/', methods=['GET', 'POST']) def index(): companies = sorted(car['company'].unique()) # 在下拉选项开头添加默认选择项,应在数据传递给模板前处理 companies = ["Select Company"] + companies car_models = sorted(car['name'].unique()) years = sorted(car['year'].unique(), reverse=True) fuel_types = car['fuel_type'].unique() return render_template('index.html', companies=companies, car_models=car_models, years=years, fuel_types=fuel_types) @app.route('/predict', methods=['POST']) def predict(): # 仅处理POST请求,避免GET请求干扰 company = request.form.get('company') car_model = request.form.get('model') year = int(request.form.get('year')) fuel_type = request.form.get('fuel_type') kms_driven = int(request.form.get('kilo_driven')) # 修正数据元素数量,匹配列数 prediction = model.predict(pd.DataFrame( columns=['name', 'company', 'year', 'kms_driven', 'fuel_type'], data=np.array([car_model, company, year, kms_driven, fuel_type]).reshape(1, 5) )) return str(np.round(prediction[0], 2)) @app.route('/predict', methods=['GET']) def predict_get(): # GET访问/predict时重定向到首页,避免无效请求 return redirect('/') if __name__ == '__main__': app.run(debug=True) # 开启debug模式便于查看错误详情
额外建议
- 开启
debug=True后,出错时会显示详细错误栈,快速定位问题。 - 确保HTML表单的字段
name属性与request.form.get()中的参数完全一致,比如name="company"、name="model"等。 - 对表单输入添加类型验证,避免非数值类型传入模型导致预测失败。
内容的提问来源于stack exchange,提问作者Ryan Nicholas Purba
相关产品推荐
相关产品推荐

