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
1 Answer
Reset to default 0Changes 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
版权声明:本文标题:python - Flask Session persistent KeyError - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736304020a1932086.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论