Answer the question
In order to leave comments, you need to log in
How to organize a session for a shopping cart in Flask?
Dear colleagues!
I am writing a flask cart based on session session["cart"], which consists of a dictionary like [{'product_id': id, 'qty': qty}] i.e. in fact, when adding a product to the cart, we add its id in the database and the quantity (qty).
<form action="/add-to-cart" method="post">
<input type="hidden" name="add_to_cart">
<input type="hidden" name="product_id" value="{{ post.id }}">
<input type="hidden" name="qty" value="1">
<button type="submit" name="add_to_cart" class="btn btn-success">Add to Cart</button>
</form>
@app.route('/add-to-cart', methods=['GET', 'POST'])
def add_to_cart():
if request.method == 'POST':
# приводим оба параметра к числу что бы сессия не материлась
id = int(request.form['product_id'])
qty = int(request.form['qty'])
cart_session() # проверяет существует ли сессия корзины и если нет, то создает её, а если да, то норм
# проверяем совпадения id product_id и если оно есть, то прибавляем количество qty к уже существующему
matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
matching[0]['qty'] += qty
session["cart"].append(dict({'product_id': id, 'qty': qty})) # добавляем товар к сессии в виде словаря
return redirect(url_for('cart'))
[{'qty': 9, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}, {'qty': 1, 'product_id': 6}]
@app.route('/add-to-cart', methods=['GET', 'POST'])
def add_to_cart():
if request.method == 'POST':
id = int(request.form['product_id'])
qty = int(request.form['qty'])
cart_session()
matching = [d for d in session['cart'] if d['product_id'] == id]
if matching:
matching[0]['qty'] += qty
else:
session["cart"].append(dict({'product_id': id, 'qty': qty}))
return redirect(url_for('home'))
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question