【问题标题】:Adding Items to Shopping Cart Python Flask将商品添加到购物车 Python Flask
【发布时间】:2019-10-10 21:41:56
【问题描述】:

我正在尝试使用 python flask 和 flask-sqlalchemy 创建 AddtoCart 和 Checkout 功能。总的来说,我认为自己是 Web 开发的初学者。如何使用按钮获取产品项目并将其作为购物车项目添加到购物车?我还想计算购物车商品的总价。

到目前为止,我创建了两个模型(ProductItem、CartItem)。我成功创建了 2 个 ProductItems(虚拟数据),并且能够使用带有 jinja2 模板的 for 循环在视图中显示它们。我尝试创建一个函数来选择产品并将其添加到购物车,但我无法弄清楚如何使添加到购物车按钮功能起作用。

提前致谢!!

class ProductItem(db.Model):
     __tablename__='products'
    id = db.Column(db.Integer,primary_key=True)
    name = db.Column(db.String(64),unique=True)
    descr = db.Column(db.Text,unique=True,nullable=True)
    price = db.Column(db.Float,nullable=False)
    img = db.Column(db.String(64),unique=True)
    cartitems = db.relationship('CartItem', backref='Product')
    def __repr__(self):
        return '<ProductName %r>' % self.name

class CartItem(db.Model):
    __tablename__='cartitems'
    id = db.Column(db.Integer,primary_key=True)
    # adding the foreign key
    product_id = db.Column(db.Integer, db.ForeignKey('products.id'))

@app.route('/')
def index():
    products = Product.query.all()
    return render_template('home.html',products=products)
def getproductitem():
    itemid = product.id
    productname = product.name
    productname = CartItem(product_id=itemid)
    db.session.add(product)
    db.session.commit()

----------------html jinja----------
{% for product in products %}
    <div class="product-item">
        <h3>{{ product.name }}</h3> 
        <img src="static/img/products/{{ product.img }}" alt="" width="200px" height="200px">
        <p> {{ product.price }}</p>
        <button onclick="getproductitem()" type="button" class="btn btn-primary">Add to Cart</button>
     </div>           
{% endfor %}

【问题讨论】:

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


    【解决方案1】:

    编辑

    意识到我没有回答有关按钮的问题。好像你正试图从 html 调用你的 python 函数(除非你的前端模板中也有一个 javascript 函数)。

    您的 python 位于服务器上,而您的 html/javascript 将位于客户端浏览器上 - 您需要通过从您的页面向服务器发送 HTTP 请求来使它们进行通信,您不能直接调用函数。

    服务器:

    @app.route('/cart/<int:product_id>', methods=['POST'])
    def add_to_cart(product_id):
    
        product = Product.query.filter(Product.id == product_id)
        cart_item = CartItem(product=product)
        db.session.add(cart_item)
        db.session.commit()
    
        return render_tempate('home.html', product=products)
    

    添加到您的 html:

    <script>
    function addToCart(productId) {
        fetch('[your.local.host.]/cart/productId', 
            {method: 'POST'}
        )
    }
    </script>
    

    更改按钮:

    <button onclick="addToCart({{product.id}})" type="button" class="btn btn-primary">Add to Cart</button>
    

    或类似的东西。您的页面需要通过 HTTP 请求与您的服务器通信。

    关于购物车的原始答案

    可能没有必要将您的购物车保留在数据库中,除非您真的希望您的用户能够在跨设备登录时访问同一个购物车,或者您预计他们需要将商品长期保存在数据库中。

    持久化会给用户请求增加不必要的时间(当您添加/检索它们时),并且 CartItem 表将继续变得越来越大,并且大多数行将变得多余(人们不太可能希望查看他们的旧购物车)购买的产品)。一种解决方案是将购物车也链接到User 表,这样每个用户只有一个购物车(前提是您的用户在购物时登录),或者确保在购买购物车后或在一定时间后删除购物车期间。

    但是,如果您不需要长期保留,请考虑将 产品 ID 存储在任一

    1. 烧瓶session。本质上是服务器上的轻量级内存存储,它链接到用户并且可以在请求处理期间访问。请参阅有关会话的教程here

    2. 在 cookie 中。 cookie 存储在浏览器(而不是服务器)中,通常使用密钥进行签名。这并不能保证它们的安全 - 它只是意味着您可以确定当您在服务器上检索它的内容时没有人修改过它的内容。查看教程here

    This article 讨论了这两种方法的一些缺点/优点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-19
      • 2020-01-14
      • 2015-03-31
      • 2018-04-10
      • 1970-01-01
      • 2017-02-07
      相关资源
      最近更新 更多