【问题标题】:Flask update product quantity in SessionSession 中 Flask 更新产品数量
【发布时间】:2021-08-26 14:59:11
【问题描述】:

我正在尝试使用 Flask 创建一个小型电子商务商店。除了购物车阶段,一切都进行得很好。我希望应用增加购物车中产品的数量,而不是两次添加相同的产品。

例如,当我点击两次“加入购物车”时,会话中保存的数据是这样的:

[{'product': '5', 'quantity': 1}]
[{'product': '5', 'quantity': 1}]

我希望它保存为:

[{'product': '5', 'quantity': 2}]

这是我当前的代码:

@app.route('/item/<id>', methods=['POST', 'GET'])
def item_page(id):
    form = add_to_cart()
    if form.validate_on_submit():
        if 'cart' in session:
            session['cart'].append({'id' : form.id.data, 'quantity' : form.quantity.data})
            session.modified = True
    return render_template('product.html', form=form)

我在这里找到了一个类似的问题,但该解决方案对我不起作用: Flask python where should I put goods that go to cart in online shop?

【问题讨论】:

    标签: python python-3.x flask flask-session


    【解决方案1】:

    您正在追加到一个列表,因此您总是在创建一个新行。

    您需要检查产品是否已存在于购物车的商品列表中,如果存在,则增加数量。类似的东西(这是非常粗略的代码)

        # Get a temporary reference to the session cart, just to reduce the name of the variable we will use subsequently
        cart = session["cart"]
    
        # This flag will be used to track if the item exists or not
        itemExists = False
    
        # Iterate over the cart contents and check if the id already exists
        for index, value in enumerate(cart):
            if value["id"] == form.id.data:
                cart[index]["quantity"] = cart[index]["quantity"] + form.quantity.data
                itemExists = True
                break # exit the for loop 
    
        # if the item does not exist, then you create a new row
        if not itemExists:
            cart.append({'id' : form.id.data, 'quantity' : form.quantity.data})
        
        # Save the temp cart back into session
        session["cart"] = cart
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 2014-08-30
      • 2015-04-16
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多