Flask Sessions
A session remembers values between requests. Flask keeps the values in a signed cookie.
Make the app
This line imports Flask and session together. The secret key lets Flask sign the session cookie.
from flask import Flask, session
app = Flask(__name__)
app.secret_key = "dev-key"Count the visits
The view reads the visit count from the session, adds one, and stores it back.
@app.route("/count")
def count():
session["visits"] = session.get("visits", 0) + 1
return "Visits: " + str(session["visits"])Visit twice
The same test client asks twice. The count grows, because the session remembers it.
client = app.test_client()
print(client.get("/count").data.decode())
print(client.get("/count").data.decode())Example
from flask import Flask, session
app = Flask(__name__)
app.secret_key = "dev-key"
@app.route("/count")
def count():
session["visits"] = session.get("visits", 0) + 1
return "Visits: " + str(session["visits"])
client = app.test_client()
print(client.get("/count").data.decode())
print(client.get("/count").data.decode())Key points
- session is a dict that lives across requests.
- session["visits"] stores a value under visits.
- The cookie carries the values to the next request.
- The secret key signs the cookie.
In this example, the view reads the visit count from the session and adds one. The test client asks for /count twice with the same client, so the cookie carries the count along. The prints show Visits: 1 and then Visits: 2.
Note
A session holds small values, not large files.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Where does Flask keep session values between requests?