Python 3.x 向购物车添加项目

Python 3.x 向购物车添加项目,python-3.x,flask,flask-sqlalchemy,Python 3.x,Flask,Flask Sqlalchemy,我正在尝试使用python flask和flask sqlalchemy创建AddtoCart和签出功能。我认为自己一般都是网络开发的初学者。如何使用按钮获取产品项目并将其作为购物车项目添加到购物车中?我还想计算购物车项目的总价格 到目前为止,我创建了两个模型ProductItem,CartItem。我成功地创建了2个ProductItems虚拟数据,并能够使用带有jinja2模板的for循环在视图中显示它们。我曾尝试创建一个函数来选择产品并将其添加到购物车,但我无法找到如何使“添加到购物车”按

我正在尝试使用python flask和flask sqlalchemy创建AddtoCart和签出功能。我认为自己一般都是网络开发的初学者。如何使用按钮获取产品项目并将其作为购物车项目添加到购物车中?我还想计算购物车项目的总价格

到目前为止,我创建了两个模型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 %}
编辑

意识到我没有回答关于按钮的问题。看起来您试图从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表将继续变得越来越大,大多数行将变得多余。人们不太可能希望在购买产品后查看他们的旧购物车。一种解决方案是将购物车链接到用户表,这样每个用户只有一个购物车,前提是您的用户在购物时登录,或者确保在购物车购买后或在特定时间段后删除购物车

但是,如果您不需要长期坚持,请考虑将产品ID存储在

烧瓶。本质上是服务器上的一个轻量级内存存储,链接到用户,可以在请求处理过程中访问。请参见有关会话的教程

在饼干里面。cookie存储在浏览器中而不是服务器中,通常使用密钥进行签名。这并不能保证它们的安全性——这只是意味着您可以确保在服务器上检索内容时,没有人修改了内容。请参阅教程

讨论两种方法的一些缺点/优点