如何在Flask中为会话添加多个项目

时间:2016-01-06 10:22:46

标签: python flask jinja2

我在我的网站上创建了一个“添加到购物车”,效果很好。

使用Jquery.getJSON发出请求以获取所选产品的价值,以下是代码:

    $(function() {
      $('a#process_menu').bind('click', function() {
        /*var amount = document.getElementById('kale').value;*/
        $.getJSON('{{url_for("get_the_order")}}', {
          menu_order: $(this).text(), price_order: $('input[name="kalkal"]').val(),
        }, function(data) {
          location.reload();
        });
        return false;
      });
    });

这是接收请求的函数:

@app.route('/get_the_order')
def get_the_order():

    global the_order_list

    try:

        the_order_list = []
        sum_list = []

        get_order = request.args.get('menu_order', 0, type=str)
        get_price = request.args.get('price_order', 0, type=str)

        the_order_list.append(get_order)
        sum_list.append(get_price)

        session['theOrder'] = ' '.join(the_order_list)
        session['price'] = ' '.join(sum_list)

        return jsonify(result=the_order_list + sum_list)

    except Exception as e:
        return redirect("menu")

这里我有一个显示所有产品的模板:

{% if entries_menu %}
    {% for menu_ent in entries_menu %}
        <div class="col-sm-6 col-md-3 col-lg-3 {{menu_ent.categorie}}">
            <div class="portfolio-item">
                <div class="hover-bg">
                    <a id="process_menu">
                        <div class="hover-text">
                            <h4 id="title">{{menu_ent.title}}</h4>
                            <small id="price">{{menu_ent.price}}</small>
                            <div class="clearfix"></div>
                            <i class="fa fa-plus add_basket"></i>
                            <div class="counter-order">
                                <div class="row">
                                    <div class="col-md-3">
                                        <form>
                                            <fieldset>
                                                <div class="form-group">
                                                    <input id="kale" name="kalkal" class="form-control" type="number" value="1" min="1" max="999" />
                                                </div>
                                            </fieldset>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <img src="../../static/{{menu_ent.path}}" class="img-responsive" alt="..." id="image-menu">
                    </a>
                </div>
                <h4 class="brand bold">{{menu_ent.title}}</h4>
                <span class="price pull-right">{{menu_ent.price}} </span><span class="amount pull-right"> {{menu_ent.amount}}</span>
                <p id="descr">{{menu_ent.descr}}</p>
            </div>
        </div>
    {% endfor %}
{% endif %}

这里我创建了这个函数,将所有产品放在数组中,并将它们显示在标题旁边的购物车所在的位置,这是所有逻辑发生的文件,它应该显示我想要的内容:

        {% if session.logged_in %}

            {% if session.theOrder %}
                <div class="confirm-cancel">
                    <a href="{{url_for('flush')}}"><i class="fa fa-close fa-3x btn-danger"></i></a>
                    <a href="{{url_for('order_dish')}}"><i class="fa fa-check fa-3x btn-success"></i></a>
                </div>
            {% endif %}

            <li class='main'><a href='/#main'><span>Main</span></a></li>
            <li class="comfort"><a href='/#ckidki' ><span>Chief</span></a></li>
            <li class="menu"><a href='/menu/' ><span>Menu</span></a></li>
            <li class="order"><a href="/order/" ><span>Make an order</span></a></li>
            <li class="contact"><a href='/#contact' ><span>Contact us</span></a></li>
            <li class="last orders"><a href='/admin/' ><span>Admin</span></a></li>

            {% if session.theOrder %}

                <li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">{{session.get('theOrder')}} &nbspx{{session.get('price')}}</p></i></li>

            {% else %}

                <li class="basket"><i class="fa fa-shopping-basket fa-3x" style="color: #fff;"><p class="pull-left" id="bask" style="font-size: 19px; font-weight: 600; font-family: "Russo One",sans-serif;">0$ &nbsp&nbsp</p></i></li>

            {% endif %}
        {% endif %}

问题是我无法获得我在会话中选择的所有产品,所以如果我检查了产品列表,我只看到一个,实际上,每次只获得点击的项目。

请,任何建议如何使这项工作,无论如何,任何帮助将是吨赞赏。

2 个答案:

答案 0 :(得分:4)

我修改了你的代码:

    the_order_list = session['theOrder']
    sum_list = session['price']

    the_order_list.append(get_order)
    sum_list.append(get_price)

    session['theOrder'] = the_order_list
    session['price'] = sum_list

答案 1 :(得分:2)

I was facing the same issue and finally got this answer!

@app.route('/addtocart/')  #加入购物车选项
def addtocart():
id = request.args.get('id')
if 'cart' not in session:
    session['cart'] = []  # 
cart_list = session['cart']
cart_list.append(id)
session['cart'] = cart_list  # 
print(session)

cart_list = session['cart'] will return an empty list. Then, after cart_list.append(id), you've got a list with length 1. The key sentence is session['cart'] = cart_list, if you don't do this, your list's maximum length is 2.