HTTP is inherently stateless, meaning each request is independent. Cookies and sessions bridge this gap, allowing a web server to recognize users across multiple requests. A cookie is a small piece of data stored on the client side in plain text, while a session uses a signed, encrypted cookie to securely store data on the client.
Setting and Retrieving Cookies
Cookies are set using response.set_cookie() on a response object. They can be read from request.cookies.
from flask import Flask, Response, request
app = Flask(__name__)
@app.route("/set_cookie")
def set_cookie():
response = Response("cookie created")
response.set_cookie("user_id", "123")
return response
@app.route("/get_cookie")
def get_cookie():
cookies = request.cookies
if cookies.get("user_id") == "123":
return f"Welcome back! Your cookies: {cookies}"
else:
return "Please obtain a cookie first."
if __name__ == '__main__':
app.run(debug=True, port=5000)
Visiting /get_cookie before /set_cookie will return the error message. After visiting /set_cookie and then /get_cookie, the browser sends the stored cookie, and the user is recognized.
Working with Sessions
Flask sessions are built on top of cookies but store data in a secure, signed format. Before using the session object, you must set a SECRET_KEY in the app configuration. This key is used to sign the session cookie, preventing tamepring.
from flask import Flask, session
app = Flask(__name__)
app.config["SECRET_KEY"] = "my_secret_key_123"
@app.route("/set_session")
def set_session():
session["user_name"] = "xiaoming"
return f"Session set for {session['user_name']}"
@app.route("/get_session")
def get_session():
if session.get("user_name") == "xiaoming":
return "Authentication successful."
else:
return "Please log in first."
if __name__ == "__main__":
app.run(debug=True, port=5001)
The session API is similar to a dictionary. Values are auotmatically serialized and signed. The SECRET_KEY must be kept secret; a common practice is to generate a random string. Without it, Flask will raise an error when a session is used.
Both cookies and sessions store data client-side. The primary difference is that session data is signed and optionally encrypted. For storing sensitive information or avoiding client-side data manipulation, sessions are the recommended approach.