Reputation: 2914
my flask session clears whenever I redirect. Python code below. I am trying to add some cart items to the session, and then be able to add more items to the cart. The issue is, whenever I do: return redirect(url_for('buy'))
, the a get request is triggered asking for the page, and when the button is pressed, when the post request is send, the session is cleared.
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)
Any help is appreciated.
BTW after clearing, when doing print(session), this is the output: <SecureCookieSession {'cart-items': {}}
Upvotes: 1
Views: 2086