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

Flask接口get_estimated_price Postman传form-data参数调用失败

问题定位

POST接口调用失败由3个可复现的代码问题导致:

  1. CORS头拼写与格式错误
    GET接口中跨域头Access-Control-Allow-Origin被换行拆分为两段,会生成带无效空格的头字段;POST接口中直接将头名错写为Access-Control-Origin,缺失核心的Allow-字段,跨域场景下会被直接拦截。
  2. 无参数校验与异常捕获
    代码直接通过request.form['key']的方式强取参数,且直接做float/int强制类型转换,只要出现参数缺失、参数名拼写不匹配、数值字段传非数字内容、传值为空任意一种情况,就会直接返回400错误,无任何明确错误提示。
  3. 隐式的参数解析风险
    若手动在Postman中设置了Content-Type: application/x-www-form-urlencoded或其他非multipart/form-data的头,会导致form-data参数无法被Flask正确解析。
修复代码

替换原有业务代码为以下版本,修复了上述问题,同时加了基础的错误提示,开启debug模式方便排查:

from flask import Flask, request, jsonify
import util
app = Flask(__name__)


@app.route('/get_location_names')
def get_location_names():
    response = jsonify({
        'locations': util.get_location_names()
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response


@app.route('/get_estimated_price', methods=['POST'])
def get_estimated_price():
    # 参数存在性校验
    required_params = ['total_sqft', 'location', 'bhk', 'bath']
    for param in required_params:
        if param not in request.form:
            return jsonify({'error': f'缺失必要参数: {param}'}), 400
    
    try:
        total_sqft = float(request.form['total_sqft'])
        location = request.form['location'].strip()
        bhk = int(request.form['bhk'])
        bath = int(request.form['bath'])
    except ValueError:
        return jsonify({'error': '参数格式错误:total_sqft需传数字,bhk、bath需传整数'}), 400

    try:
        estimated_price = util.get_estimated_price(location, total_sqft, bhk, bath)
    except Exception as e:
        return jsonify({'error': f'价格计算失败: {str(e)}'}), 500

    response = jsonify({'estimated_price': estimated_price})
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response


if __name__ == "__main__":
    print("starting Python Flask Server for Home Price Prediction....")
    util.load_saved_Artifacts()
    # 开启debug模式,控制台会输出完整报错栈
    app.run(debug=True)
Postman调用注意事项
  • 请求方法必须选POST,地址和GET接口同域名同端口,路径为/get_estimated_price
  • 请求体选form-data,不要手动设置Content-Type请求头,Postman会自动生成带合法boundary的头
  • 传入的location值必须是get_location_names接口返回的有效值,前后不要带空格
  • total_sqft、bhk、bath三个字段直接传纯数字,不要带单位、特殊字符

内容的提问来源于stack exchange,提问作者swati agrawal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:09:23