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

Python Flask模板中解析追加字典列表实现购物车多商品展示

问题解决方法

核心问题说明

  • 后端存储逻辑错误:每次请求时都重新初始化append_list,导致前序添加的商品数据全部丢失,无法实现多商品追加效果。Flask请求本身无状态,需要借助session存储单个用户的跨请求购物车数据。
  • 模板遍历逻辑错误:遍历列表时写死索引[0],仅能获取列表第一个元素,即使遍历正确的列表也无法正常输出所有商品。

后端代码修正

首先需要在Flask实例中配置加密密钥用于session存储,在你的启动文件中添加:

app.secret_key = "自定义的随机加密字符串,生产环境请妥善保管"

之后修改路由逻辑:

@app.route('/<int:id>/cart', methods=['GET', 'POST'])
def add_to_cart(id):
    tag = get_tag(id)
    sub_total = 0
    # 先从session中获取已有的购物车列表,没有则初始化为空
    append_list = session.get('append_list', [])
    
    try:
        product_quantity = 300
        user_quantity = 10

        if user_quantity > product_quantity:
            flash("Please enter a lower quantity.")
            return render_template('tag.html', tag=tag)

        else:
            tag_id = 12
            product = "Title"
            price = 300
            sub_total = "{:.2f}".format( user_quantity * price )
            price = "{:.2f}".format(price)

            product_item = {
                "id": tag_id,
                "product": product,
                "price": price,
                "user-quantity": user_quantity,
                "product-quantity": product_quantity,
                "subtotal": sub_total
            }
            # 新商品追加到已有购物车列表
            append_list.append(product_item)
            # 存回session并标记已修改
            session['append_list'] = append_list
            session.modified = True
            
            flash("Added to cart.")
            
    except Exception as e:
        print(e.args)

    return render_template('cart.html', tag=tag, sub_total=sub_total, append_list=append_list)

如果需要清空购物车,可在对应逻辑中添加session.pop('append_list', None)即可。生产环境建议将购物车数据持久化存储到数据库,session仅适合临时存储场景。

模板代码修正

直接遍历传入的append_list,使用循环变量item获取当前商品的属性即可:

{% for item in append_list %}
<tr>
  <td>{{ item['product'] }}</td>
  <td>{{ item['price'] }}</td>
  <td>{{ item['user-quantity'] }}</td>
  <td>{{ item['subtotal'] }}</td>
</tr>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:45:03