从session[]Python获取数据,Flask

Getting data from the session[] Python, Flask

我正在尝试使用 Python 和框架 - Flask 为在线商店制作简单的购物车系统。 我从 products.html 中的表单获取数据,然后将其写入会话。我在获取此数据并将其返回到 cart.html 时遇到问题 - 我得到的只是清晰的页面,而不是我添加到购物车的产品名称。

products.html

    {% for el in products %}
        <p>Name {{ el.product_name }}</p>
        <p>Description {{ el.product_description }}</p>
        <p>Image </p> <img width="200" height="200" src="data:;base64,{{ el.product_img }}">
        <p>Cost: {{ el.product_cost }} тенге.</p>

        <form method="post" action="/cart">
            <input type="hidden" name="cart_prod_name" value="{{ el.product_name }}">
            <input type="submit" value="Add to cart">
        </form>
    {% endfor %}

Python 函数 cart():

@app.route('/cart', methods=['POST', 'GET'])
def cart():
    if 'cart' not in session:
        session['cart'] = []

    if request.method == 'POST':
        cart_prod_name = request.form['cart_prod_name']
        session['cart'] += cart_prod_name
        return redirect('/cart')

    if request.method == 'GET':
        cart_products = session['cart']
        return render_template('cart.html', cart_products=cart_products)

cart.html:

{% for cart_product in cart_products %}
    <p>{{ cart_product.order_prod_name }}</p>
{% endfor %}

来自 flask.session 文档:

Be advised that modifications on mutable structures are not picked up automatically, in that situation you have to explicitly set the attribute to True yourself.

您的购物车持有人对象是一个可变结构 == 列表,因此您必须在更改后进行设置

session.modified = True

我解决了这个问题。确切地说,我需要在 cart_roducts 中迭代 cart_product 并输出 cart_product 而不要调用它来输出 order_prod_name.

固定cart.html:

{% for cart_product in cart_products %}
    <p>{{ cart_product }}</p>
{% endfor %}