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

Flask+Bootstrap实现表单选择后执行脚本并展示表格结果

实现步骤

一、修改Python后端代码

调整路由支持POST请求,获取表单参数,解析脚本返回的字符串并计算所需统计值,最后传递给前端模板:

from flask import Blueprint, render_template, request
from flask_login import login_required

core_bp = Blueprint("core", __name__)

def getPrices(service, country):
    if service == "1" and country == "uk":
        return "1.25:7000\n2.75:13000\n6.40:50400"
    # 可在此扩展更多service与country的匹配逻辑
    return ""

@core_bp.route("/", methods=["GET", "POST"])
# @login_required
def home():
    price_data = []
    min_price = None
    total_stock = 0

    if request.method == "POST":
        country = request.form.get("country")
        service = request.form.get("service")
        # 验证两个选项均已选择
        if country and service:
            raw_result = getPrices(service, country)
            if raw_result:
                # 逐行解析返回数据
                for line in raw_result.strip().split("\n"):
                    price_str, stock_str = line.split(":")
                    price = float(price_str)
                    stock = int(stock_str)
                    price_data.append({"price": price, "stock": stock})
                # 计算最低价格
                min_price = min(item["price"] for item in price_data)
                # 计算总库存
                total_stock = sum(item["stock"] for item in price_data)

    return render_template("core/index.html", 
                           price_data=price_data, 
                           min_price=min_price, 
                           total_stock=total_stock)

二、修改前端模板代码

给下拉框添加表单提交所需的name属性,添加提交按钮,并实现结果区域的条件渲染:

{% extends "_base.html" %}
{% block content %}
{% if current_user.is_authenticated %}
<h3 class="text-center">Welcome {{current_user.email}}!</h3>
{% else %}
<h3 class="text-center">Price List</h3>
{% endif %}
<br>
<div class="form-group">
<form action="" method="post">
<div class="input-group mb-3-center" style="display: flex;justify-content: center; gap: 2rem;">
    <div>
    <label for="country">Country</label>
    <br>
    <select class="selectpicker" title="Choose a country..." data-live-search="true" id="country" name="country">
      <option value="uk">United Kingdom</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>
    </div>
    <div>
    <label for="service">Service</label>
    <br>
    <select class="selectpicker" title="Choose a service..." data-live-search="true" id="service" name="service">
      <option value="1">One</option>
      <option value="2">Two</option>
      <option value="3">Three</option>
    </select>
    </div>
    <div style="align-self: flex-end;">
    <button type="submit" class="btn btn-primary">Submit</button>
    </div>
</div>

<!-- 提交后展示结果区域 -->
{% if price_data %}
<div class="mt-4 text-center">
    <h4>Summary</h4>
    <p>Lowest Price: ${{ min_price }}</p>
    <p>Total Stock: {{ total_stock }}</p>
</div>

<div class="mt-4">
    <table class="table table-bordered table-striped text-center">
        <thead>
            <tr>
                <th>Price</th>
                <th>Stock</th>
            </tr>
        </thead>
        <tbody>
            {% for item in price_data %}
            <tr>
                <td>${{ item.price }}</td>
                <td>{{ item.stock }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
{% endif %}
</form>
</div>
{% endblock %}

三、关键细节说明

  • 表单参数绑定:必须给下拉框添加name属性,Flask才能通过request.form获取提交的选项值。
  • 数据校验:后端先判断两个选项是否都已选择,避免空值传递给脚本。
  • 条件渲染:模板通过{% if price_data %}控制结果区域的显示,只有提交后有数据时才展示汇总信息和表格。
  • 数据转换:将脚本返回的字符串转换成数值类型,方便后续的统计计算和前端格式化展示。

内容的提问来源于stack exchange,提问作者big boss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:53:20