You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask服务predict_home_price接口请求无法识别错误求助

Flask房价预测接口Bad Request错误排查

问题概述

已训练完成房价预测模型,通过Flask提供服务,/hi和/locations接口可正常返回数据,但访问/predict_home_price接口时出现错误:"The browser (or proxy) sent a request that this server could not understand.",Postman测试也返回Bad Request。

错误原因及修复方案

1. 模型相关变量未初始化

原因:util.py中的load_saved_artifacts()函数仅在自身作为主模块运行时被调用,Flask服务启动时并未执行该函数,导致__locations、__area、__model均为None。当接口调用util.get_estimated_price()时,访问这些变量会触发异常,最终导致Bad Request。

修复:在server.py启动前调用util.load_saved_artifacts():

if __name__ == '__main__':
    util.load_saved_artifacts()  # 添加这一行
    print('python flask started')
    app.run()

2. 请求方式与参数获取逻辑不匹配

原因:接口声明支持GET和POST方法,但代码中仅用request.form获取参数——GET请求的参数在request.args中,而非request.form,直接访问request.form['key']会抛出KeyError,导致Flask返回Bad Request。

修复:

  • 方案一:限定接口仅支持POST方法(推荐,因为涉及数据提交),修改路由定义:
    @app.route('/predict_home_price', methods=['POST'])
    
  • 方案二:兼容GET和POST的参数获取:
    def predict_home_price():
        # 优先从form获取,没有则从args获取
        total_sqft = float(request.values.get('total_sqft'))
        location = request.values.get('location')
        size = int(request.values.get('size'))
        bath = int(request.values.get('bath'))
        area_type = request.values.get('area_type')
        balcony = int(request.values.get('balcony'))
        # ... 后续代码不变
    

3. 参数缺失或格式错误未处理

原因:如果请求中缺少任意参数,或者参数格式不符合要求(比如字符串转数字失败),会直接抛出异常,导致请求无法正常解析。

修复:添加参数校验和异常捕获,返回明确的错误信息:

@app.route('/predict_home_price', methods=['POST'])
def predict_home_price():
    try:
        total_sqft = float(request.form.get('total_sqft'))
        location = request.form.get('location')
        size = int(request.form.get('size'))
        bath = int(request.form.get('bath'))
        area_type = request.form.get('area_type')
        balcony = int(request.form.get('balcony'))
        
        # 校验参数是否为空
        required_params = [total_sqft, location, size, bath, area_type, balcony]
        if any(param is None for param in required_params):
            return jsonify({'error': '缺少必要参数'}), 400
        
        # 校验location和area_type是否合法
        if location not in util.locations():
            return jsonify({'error': '无效的location值'}), 400
        if area_type not in util.areas():
            return jsonify({'error': '无效的area_type值'}), 400
            
        response = jsonify({
            'estimated_price': util.get_estimated_price(area_type, location, size, total_sqft, bath, balcony)
        })
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    except ValueError as e:
        return jsonify({'error': f'参数格式错误:{str(e)}'}), 400
    except Exception as e:
        return jsonify({'error': f'服务器内部错误:{str(e)}'}), 500

4. 跨域预检请求未处理(可选)

原因:如果前端通过浏览器跨域访问接口,会先发送OPTIONS预检请求,当前接口未处理该请求类型,可能导致请求失败。

修复:使用flask-cors库简化CORS处理:

  1. 安装依赖:pip install flask-cors
  2. 在server.py中配置:
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 全局开启CORS,无需手动添加headers

验证步骤

  1. 启动Flask服务,确认控制台输出loading saved artifacts...start和loading artifacts is done。
  2. 使用Postman发送POST请求,设置Content-Type为application/x-www-form-urlencoded,并传入所有必填参数:
    • total_sqft: 1056
    • location: Electronic City Phase II
    • size: 2
    • bath: 2
    • area_type: Super built-up Area
    • balcony: 1
  3. 检查返回结果是否正常,应该得到类似{"estimated_price": 39.07}的响应。

内容的提问来源于stack exchange,提问作者Deepak Mittal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:30:58