首页 > 解决方案 > 将商品添加到购物车 Python Flask

问题描述

我正在尝试使用 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.xflaskflask-sqlalchemy

解决方案


编辑

意识到我没有回答有关按钮的问题。似乎您正试图从 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。本质上是服务器上的轻量级内存存储,它链接到用户并且可以在请求处理期间访问。在此处查看有关会话的教程。

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

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


推荐阅读