Flask sessions
This example fails when two or more people use the site concurrently:shopping cart fail.py
from flask import * app = Flask(__name__) cart = [] cartPage = ''' <form action="/buy" method="POST"> <input type="radio" name="drink" value="coke"> coke <br> <input type="radio" name="drink" value="mdew"> mdew <br> <input type="submit" value="buy"> </form> {% if myCart is defined %} <h3>Drinks purchased:</h3> {% for each_item in myCart %} {{ each_item }}<br> {% endfor %} {% endif %}''' @app.route("/buy", methods=["POST"]) def bought(): cart.append(request.form["drink"]) return render_template_string(cartPage, myCart=cart) @app.route("/") def start(): return render_template_string(cartPage) app.run(debug=True)
To fix this, we need a specific variable for each user that can be accessed (for that user) via multiple pages. This type of variable is called a session variable.
The following examples above show session variables in use:
session variable.py
from flask import * app = Flask(__name__) app.secret_key = "sssshhhhhhhhh!" loginPage = ''' {% if user is not defined %} <form action="/login" method="POST"> <input type="text" name="username"<br> <input type="submit" value="log in"> </form> {% else %} <p>Welcome {{ user }}. <a href="/logout">logout</a></p> {% endif %}''' @app.route("/login", methods=["POST"]) def login(): session["myName"] = request.form["username"] return render_template_string(loginPage, user=session["myName"]) @app.route("/") def launch(): return render_template_string(loginPage) @app.route("/logout") def logout(): session.pop("myName", None) return redirect("/") app.run(debug=True)
shopping cart better.py
from flask import * app = Flask(__name__) app.secret_key = "sssshhhhhhhhh!" cartPage = ''' <form action="/buy" method="POST"> <input type="radio" name="drink" value="coke"> coke <br> <input type="radio" name="drink" value="mdew"> mdew <br> <input type="submit" value="buy"> </form> {% if myCart is defined %} <h3>Drinks purchased:</h3> {% for each_item in myCart %} {{ each_item }}<br> {% endfor %} {% endif %}''' @app.route("/buy", methods=["POST"]) def bought(): temp = session["cart"] temp.append(request.form["drink"]) session["cart"] = temp return render_template_string(cartPage, myCart=session["cart"]) @app.route("/") def start(): if "cart" not in session: session["cart"] = [] return render_template_string(cartPage) app.run(debug=True)