【问题标题】:Flask python where should I put goods that go to cart in online shop?Flask python 我应该把去网上商店购物车的商品放在哪里?
【发布时间】:2016-02-19 21:23:15
【问题描述】:

我正在用烧瓶和 python 3 建立一个简单的商店。 我有表 goods ,现在我有一个简单的问题。 我没有用户注册,不用注册就可以买商品了。

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

如果我有注册,我可以制作另一个表格,我可以在其中保存 user_id good_id 和我需要的任何东西。

但在我的情况下,我应该使用一些会话范围的变量吗? 根据这个answer - 是的。
那么您能否提供一个创建和修改此会话范围变量的示例? 我尝试用谷歌搜索一些链接,例如this ,但仍不清楚。

【问题讨论】:

  • 您也可以为用户分配一个唯一的 id,然后使用一个表,就好像您知道用户是谁一样。这将具有购物车在访问之间持续存在的优势(即关闭浏览器)。然后,您还需要进行例行的房屋清洁(从数据库中清除旧会话)。已知用户和匿名用户之间唯一真正的区别是您知道他们的名字。根据您的需要使用会话和/或数据库。

标签: python session python-3.x flask


【解决方案1】:

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

下面是一些示例代码:

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

这只是一个基本示例。

【讨论】:

  • 这对我很有用,谢谢!我只有一个问题 - 为什么在创建新购物车时需要 .format(id)
  • 这实际上没有必要,实际上并没有做任何事情。我应该删除它。
猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 2011-12-04
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2017-10-14
  • 2013-04-14
  • 1970-01-01
相关资源
最近更新 更多