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

Python Flask中输入值变动时是否有方法更新已过滤的字典?

问题核心原因
  • 你直接在index路由中作为普通函数调用calcprice()时,不会携带用户提交表单的请求上下文,调用时的请求对象是属于/路由的GET请求,永远没有POST表单数据,所以永远只能拿到默认价格120000
  • 两个路由属于完全独立的请求,表单提交到/calcprice后不会自动触发/页面的重新渲染,自然无法同步更新过滤结果
解决方案

方案1:整页刷新(实现成本最低)

将表单提交逻辑合并到index路由,无需单独维护/calcprice路由,提交表单后自动刷新页面返回最新筛选结果:

后端代码修改

from flask import request, render_template

# 提取价格计算逻辑为公共工具函数,不绑定路由
def get_max_price(post_data=None):
    default_price = 120000
    if post_data and "Income" in post_data:
        return int(post_data["Income"])
    return default_price

# index路由支持POST方法接收表单提交
@app.route('/', methods=['GET', 'POST'])
def index():
    # 获取当前可承担的最高房价
    max_price = get_max_price(request.form)
    # 处理房产数据
    output_dict = purchaseDF.to_dict(orient='records')
    for sub in output_dict:
        # 原代码多余的内层for key in sub循环可直接删除,无需重复遍历所有键
        sub['ListPrice'] = float(sub['ListPrice'])
    # 过滤结果
    filtered_houses = [d for d in output_dict if d['ListPrice'] <= max_price]
    # 将结果和当前价格传入模板渲染
    return render_template('index.html', houses=filtered_houses, current_price=max_price)

前端模板表单示例

<!-- 表单直接提交到当前index路由 -->
<form method="POST" action="/">
  <input type="number" name="Income" value="{{ current_price }}" required>
  <button type="submit">筛选房产</button>
</form>
<!-- 后续遍历houses变量渲染房产列表即可 -->

方案2:无刷新更新(体验更好)

通过Ajax异步提交表单,拿到最新过滤结果后局部更新页面,无需整页刷新:

新增后端过滤接口

from flask import jsonify

@app.route('/api/filter', methods=['POST'])
def filter_api():
    # 接收前端传的价格参数
    max_price = float(request.json.get("max_price", 120000))
    output_dict = purchaseDF.to_dict(orient='records')
    for sub in output_dict:
        sub['ListPrice'] = float(sub['ListPrice'])
    filtered = [d for d in output_dict if d['ListPrice'] <= max_price]
    return jsonify({"houses": filtered})

前端异步请求示例

document.querySelector('form').addEventListener('submit', async (e) => {
  e.preventDefault();
  const inputPrice = document.querySelector('input[name="Income"]').value;
  // 异步请求过滤结果
  const res = await fetch('/api/filter', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({max_price: inputPrice})
  });
  const data = await res.json();
  // 调用渲染函数更新页面列表,无需刷新
  renderHouseList(data.houses);
})

内容的提问来源于stack exchange,提问作者Rob Thompson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 18:27:00