Flask重定向导致会话信息未被修改
我正在用基于cookie的会话来记录购物车的内容。
我刚刚添加了一个函数,用于从购物车的商品列表中移除单个商品。但我遇到了一个问题,URL的重定向似乎无法按预期工作。
因此,当我向 /remove_item/ 发送一个包含 item_index 和 0 的表单时,表单能够被正确接收。
相应地,列表中对应的项已被移除。
但在完成对 /shopping_cart 的重定向后,值仍然保持原样。
因此,购物车中的商品清单仍未被修改。
这里到底出了什么问题?我该如何把更新后的会话信息传递给 /shopping_cart?
@app.route('/remove_item/<int:item_index>', methods=['POST'])
def remove_item(item_index): # correct index number received
if request.method == 'POST':
print(len(session['cart'])) # prints 3
del session["cart"][item_index]
print(len(session['cart'])) # prints 2 and the desired list item is removed
return redirect(url_for("shopping_cart"))
@app.route('shopping_cart', methods=['GET', 'POST'])
def shopping_cart():
print(len(session['cart'])) # prints 3, should be 2
return render_template('shopping_cart.html')
解决方案
对于会话内存中的可变结构,修改不会自动生效。为此,有一个属性 modified,可以手动赋值一个布尔值 True。这将确保修改生效。
session.modified = True
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。