【问题标题】:Getting data from the session[] Python, Flask从会话中获取数据[] Python, Flask
【发布时间】:2020-11-30 12:51:23
【问题描述】:

我正在尝试使用 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 %}

【问题讨论】:

    标签: python html session flask


    【解决方案1】:

    来自flask.session docs:

    请注意,不接受对可变结构的修改 自动,在这种情况下,您必须明确设置 归因于 True 自己。

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

    session.modified = True
    

    【讨论】:

    • 我试过了,得到了同样的结果——只是清除页面
    • 好的,您可以在 POST print(request.form['cart_prod_name']) 时调试表单中的内容吗?也不要用list += str,有一个方法list.append(str)
    • 也可以直接在模板中获取会话对象。将此添加到您的模板{{session['cart']|pprint}}
    • request.from['cart_prod_name'] 给我product_name,例如我得到product1。我还调试了将此名称写入会话并且它有效,我可以在session['cart'] 中写入product1。我只需要从那里获取这个名称并将其放入 html 模板中
    • 我还尝试查看我的 cart.html 页面的元素代码,我有 &lt;p&gt; 标签,其中应该是来自 session['cart'] 的产品名称
    【解决方案2】:

    我解决了这个问题。正是我需要在cart_roducts 中迭代cart_product 并输出cart_product 而不要调用它来输出order_prod_name

    固定cart.html:

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

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 2015-10-31
      • 2017-06-15
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多