我应该把网店里购物车里的商品放在哪里?

2024-05-29 05:58:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用烧瓶和python3建立一个简单的商店。 我有表goods,现在我有一个简单的问题。 我没有用户注册,你可以直接购买没有注册的商品。在

所以当我点击按钮add to cart时,我应该把所选货物的id和数量放在哪里?在

如果我有注册,我可以做另一个表,在那里我可以保存user_idgood_id和我需要的任何东西。在

但在我的例子中,我应该使用一些会话范围的变量吗? 根据这个answer-是的。
你能给我一个创建和修改这个会话范围变量的例子吗? 我试着用谷歌搜索一些类似this 的链接,但还是不清楚。在


Tags: toaddid数量烧瓶按钮python3例子
1条回答
网友
1楼 · 发布于 2024-05-29 05:58:01

你应该使用烧瓶疗法。请参阅文档:

下面是一些示例代码:

from flask import Blueprint, render_template, abort, session, flash, redirect, url_for

@store_blueprint.route('/product/<int:id>', methods=['GET', 'POST'])
def product(id=0):
    # AddCart is a form from WTF forms. It has a prefix because there
    # is more than one form on the page. 
    cart = AddCart(prefix="cart")

    # This is the product being viewed on the page. 
    product = Product.query.get(id)


    if cart.validate_on_submit():
        # Checks to see if the user has already started a cart.
        if 'cart' in session:
            # If the product is not in the cart, then add it. 
            if not any(product.name in d for d in session['cart']):
                session['cart'].append({product.name: cart.quantity.data})

            # If the product is already in the cart, update the quantity
            elif any(product.name in d for d in session['cart']):
                for d in session['cart']:
                    d.update((k, cart.quantity.data) for k, v in d.items() if k == product.name)

        else:
            # In this block, the user has not started a cart, so we start it for them and add the product. 
            session['cart'] = [{product.name: cart.quantity.data}]


        return redirect(url_for('store.index'))

这只是一个基本的例子。在

相关问题 更多 >

    热门问题