admin管理员组

文章数量:1122832

I'm building a simple webshop where products in basket are stored in the session dictionary before the user registered (after the information is stored in SQL). The error-handling is not delivering the expected result and I cannot figure out why.

Intention:

  • When adding the first product, the key "basket" doesn't exist yet PATH > KeyError KeyError
  • When adding the first product of it's kind, the respective key "product_id" doesn't exist yet PATH > KeyError Try
  • When another product of the same kind is added, the value is increased by one > PATH Try Try

The print("hit") are present to see which route the code actually takes. Even when adding a second product of the same kind the first KeyError is triggered. Why does it go that route?

enter code [email protected]("/product_to_basket/<product_id>")
def add_product_basket(product_id):
try:
    session["basket"][product_id] += 1
    print("hit1")
except KeyError:
    try:
        session["basket"].update({product_id: 1})
        print("hit2")
    except KeyError:
        session.update({"basket": {product_id: 1}})
        print("hit3")

I'm building a simple webshop where products in basket are stored in the session dictionary before the user registered (after the information is stored in SQL). The error-handling is not delivering the expected result and I cannot figure out why.

Intention:

  • When adding the first product, the key "basket" doesn't exist yet PATH > KeyError KeyError
  • When adding the first product of it's kind, the respective key "product_id" doesn't exist yet PATH > KeyError Try
  • When another product of the same kind is added, the value is increased by one > PATH Try Try

The print("hit") are present to see which route the code actually takes. Even when adding a second product of the same kind the first KeyError is triggered. Why does it go that route?

enter code [email protected]("/product_to_basket/<product_id>")
def add_product_basket(product_id):
try:
    session["basket"][product_id] += 1
    print("hit1")
except KeyError:
    try:
        session["basket"].update({product_id: 1})
        print("hit2")
    except KeyError:
        session.update({"basket": {product_id: 1}})
        print("hit3")
Share Improve this question asked Nov 22, 2024 at 11:40 ElvisJrElvisJr 12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Changes to mutable structures within the session are not automatically applied. In this case, you must explicitly set the session.modified attribute to True yourself.

@app.route('/product_to_basket/<int:product_id>')
def add_product_basket(product_id):
    if 'basket' not in session:
        session['basket'] = {}
    if product_id not in session['basket']:
        session['basket'][product_id] = 0 
    session['basket'][product_id] += 1
    session.modified = True
    # ...

本文标签: pythonFlask Session persistent KeyErrorStack Overflow