D
D
Denis2015-09-16 11:55:46
Flask
Denis, 2015-09-16 11:55:46

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>


My creation looks like this:
@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'))


It turns out the following picture when adding the same product:
[{'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}]

When adding a product, my crappy algorithm adds the quantity to the first dictionary each time, but also adds the same product to the cart session.

Necessary:
  1. Check if a product exists in the cart session by id
  2. If it exists, do not add it as a new item, but simply increase its quantity (qty) in the session.

============================================
Solution
@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

1 answer(s)
A
angru, 2015-09-16
@angru

I don't know much about Flask, but what's wrong with a dictionary instead of a list?

cart = session.setdefault('cart', {})
cart[product_id] = cart.get(product_id, 0) + qty

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question