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



我正在用flask和python 3构建一个简单的商店。我有goods表,现在我有一个简单的问题。我没有用户注册,你可以在没有它的情况下购买商品。

那么,当我点击按钮add to cart时,我应该把所选商品的id和数量放在哪里?

如果我注册了,我可以制作另一张表,在那里我可以保存user_id good_id和我需要的任何东西。

但在我的情况下,我应该使用一些会话范围的变量吗?根据这个答案——是的
那么,你能给我一个创建和修改这个会话范围变量的例子吗?我试着在谷歌上搜索一些这样的链接,但仍然不清楚。

您应该使用烧瓶会话。请参阅文档:

以下是一些示例代码:

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'))

这只是一个基本的例子。

最新更新