烧瓶蟒蛇我应该把商品放在网上商店去购物车?

问题描述 投票:0回答:1

我正在建造一个带烧瓶和蟒蛇3的简单商店。我有桌子goods,现在我有一个简单的问题。我没有用户注册,你可以在没有它的情况下购买商品。

因此,当我点击按钮add to cart时,我应该在哪里放置所选商品的ID及其数量?

如果我有注册,我可以制作另一张桌子,我可以保存user_id good_id和我需要的任何东西。

但在我的情况下,我应该使用一些会话作用域变量?根据这个answer - 是的。 那么你能给我一个创建和修改这个会话范围变量的例子吗?我试图google google像this 这样的链接,但仍然不清楚。

python session python-3.x flask
1个回答
2
投票

你应该使用flask Sessions。请参阅文档:

这是一些示例代码:

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

这只是一个基本的例子。

© www.soinside.com 2019 - 2024. All rights reserved.