重新定向时烧瓶会话清除

时间:2020-06-24 23:20:15

标签: python session flask redirect

每当我重定向时,flask会话都会清除。下面的Python代码。我正在尝试向会话中添加一些购物车项目,然后能够向购物车中添加更多项目。问题是,每当我执行return redirect(url_for('buy'))时,都会触发一个get请求以请求页面,并且当按下按钮时,在发送发布请求时,将清除会话。

from flask import *
from flask_pymongo import PyMongo
from flask_bootstrap import Bootstrap

app = Flask(__name__)

app.config['MONGO_URI'] = "mongodb://localhost:27017/one-stop-shop"
app.secret_key = 'asdfasdfasdf asdfa saf sdafw er wafe  wf waef wa we awe dsf sadl f;jaosidf hopwji'

Bootstrap(app)
mongo = PyMongo(app)


@app.route('/')
def home():
    return render_template('home.html')


@app.route('/add', methods=['GET', 'POST'])
def add():
    if request.method == 'GET':
        return render_template('add.html')
    elif request.method == 'POST':
        doc = {}
        for item in request.form:
            if item != 'add':
                doc[item] = request.form[item]
        mongo.db.products.insert_one(doc)
        return redirect('/')


@app.route('/buy', methods=['GET', 'POST'])
def buy():
    if request.method == 'GET':
        session['cart-items'] = {}
        items = list(mongo.db.products.find({}))
        return render_template('buy2.html', products=items)
    elif request.method == 'POST':
        try:
            print(session)
            items2 = session['cart-items']
        except KeyError:
            items2 = {}
        items = {}
        for name, value in request.form.items():
            items[name] = value
        print(items, 1)
        if items2 != {}:
            for key, value in items.items():
                if key in items2:
                    if items[key] + items2[key] > mongo.db.products.find({'_id': key}):
                        items[key] = mongo.db.products.find({'_id': key})['Quantity Limit']
                    else:
                        items[key] += items2[key]
        session['cart-items'] = items
        print(items, 2)
        print(items2, 3)
        print(session)
        print(session['cart-items'])
        return redirect(url_for('buy'))

if __name__ == '__main__':
    app.run(debug=True)

感谢您的帮助。 顺便说一句,清除后,执行print(session)时,输出为:<SecureCookieSession {'cart-items': {}}

1 个答案:

答案 0 :(得分:1)

在重定向之前尝试设置session.modified = true

来自docs

请注意,可变结构的修改不会自动进行,在这种情况下,您必须自己将属性明确设置为True。