Session Variables
template.html:
<!doctype html> <title>shopping cart</title> <form action="/buy" method="post"> <input type="radio" name="drink" value="coke"> coke <input type="radio" name="drink" value="lemonade"> lemonade <input type="submit" value="buy"> </form> {% if myCart is defined %} <h3>purchases so far:</h3> {% for each_item in myCart %} <i>{{ each_item }}</i><br> {% endfor %} {% endif %}site.py:
from flask import Flask from flask import render_template from flask import request app = Flask(__name__) cart = [] @app.route("/buy", methods=["POST"]) def bought(): cart.append(request.form["drink"]) return render_template("template.html", myCart = cart) @app.route("/") def start(): return render_template("template.html") app.run(host="0.0.0.0", port=5000, debug=True)works fine until 2 users use the site concurrently - they end up putting items in the same trolley... a better way, store information specific to each user via a session object - replace site.py:
from flask import Flask from flask import render_template from flask import request from flask import session app = Flask(__name__) cart = [] @app.route("/buy", methods=["POST"]) def bought(): cart = session["cart"] cart.append(request.form["drink"]) session["cart"] = cart return render_template("template.html", myCart = cart) @app.route("/") def start(): session["cart"] = cart return render_template("template.html") app.secret_key = "ssssshhhhh" app.run(host="0.0.0.0", port=5000, debug=True)