简体   繁体   English

从会话中获取数据[] Python, Flask

[英]Getting data from the session[] Python, Flask

I'm trying to make simple cart system to the online shop using Python and framework - Flask.我正在尝试使用 Python 和框架 - Flask 为在线商店制作简单的购物车系统。 I'm getting data from form in products.html then writing it into the session.我从 products.html 的表格中获取数据,然后将其写入 session。 I have a problem with getting this data and returning it to the cart.html - I'm get just clear page instead of names of the products i added to the cart.我在获取此数据并将其返回到购物车时遇到问题。html - 我得到的只是清晰的页面,而不是我添加到购物车的产品名称。

products.html产品.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 function cart() : Python function 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:购物车.html:

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

From flask.session docs:来自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.请注意,对可变结构的修改不会自动拾取,在这种情况下,您必须自己将属性显式设置为 True。

your carts holder object is a mutable structure == list so you have to set after changes您的购物车架 object 是一个可变结构 == 列表,因此您必须在更改后进行设置

session.modified = True

I sloved that problem.我解决了这个问题。 Exactly I needed to iterate cart_product in cart_roducts and output cart_product and don't call it to output order_prod_name .正是我需要在cart_roducts和 output cart_product cart_product不要将它调用到 output order_prod_name

Fixed cart.html :固定cart.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM