Flask - Cookies
Flask – Cookies
Section titled “Flask – Cookies”HTTP Cookies are small pieces of data stored by the web browser on the client’s computer. Websites use them to remember information about the user across multiple requests, such as login status, preferences, or items in a shopping cart. Cookies are sent back to the server with every subsequent request to the same domain.
How Cookies Work in Flask
Section titled “How Cookies Work in Flask”- Setting Cookies: Cookies are set on the response object. You typically create a response using
make_response()and then use theresponse.set_cookie()method. - Reading Cookies: Incoming cookies sent by the browser are available in the
request.cookiesdictionary-like object. - Cookie Attributes: Besides the key and value, you can set attributes like
max_age(lifetime in seconds),expires(specific expiry date/time),path(URL path restriction),domain(domain restriction),secure(send only over HTTPS), andhttponly(prevent JavaScript access).
Example: Setting and Reading a Cookie
Let’s create an application that asks for the user’s name, stores it in a cookie, and then greets them using the stored name on subsequent visits.
- Create
templates/ask_name.html:
<!DOCTYPE html><html><head><title>Enter Name</title></head><body> <h1>What's your name?</h1> <form action="{{ url_for('set_user_cookie') }}" method="post"> <p>Name: <input type="text" name="username" required></p> <p><input type="submit" value="Save Name"></p> </form></body></html>- Create
templates/show_greeting.html:
<!DOCTYPE html><html><head><title>Greeting</title></head><body> <h1>Hello, {{ user_name_from_cookie }}!</h1> <p>Your name was remembered using a cookie.</p> <p><a href="{{ url_for('clear_user_cookie') }}">Forget My Name</a></p></body></html>- Create the Flask application (
app.py):
from flask import Flask, render_template, request, make_response, redirect, url_forimport datetime
app = Flask(__name__)
@app.route('/')def index(): # Check if the username cookie exists username = request.cookies.get('username') if username: # If cookie exists, show greeting return render_template('show_greeting.html', user_name_from_cookie=username) else: # If no cookie, ask for name return render_template('ask_name.html')
@app.route('/setcookie', methods=['POST'])def set_user_cookie(): if request.method == 'POST': user = request.form['username']
# Create a response object based on redirecting back to index response = make_response(redirect(url_for('index')))
# Set the cookie 'username' with the value 'user' # Set max_age for persistence (e.g., 1 year) max_age_seconds = 365 * 24 * 60 * 60 expires_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age_seconds)
response.set_cookie('username', user, max_age=max_age_seconds, expires=expires_time, httponly=True, # Recommended: Cookie not accessible via JavaScript samesite='Lax') # Recommended: Helps prevent CSRF
return response # Handle non-POST requests if necessary (optional) return redirect(url_for('index'))
@app.route('/clearcookie')def clear_user_cookie(): response = make_response(redirect(url_for('index'))) # Delete the cookie by setting an empty value and expiry in the past response.set_cookie('username', '', expires=0) return response
if __name__ == '__main__': app.run(debug=True)Run the application and visit http://127.0.0.1:5000/.
Description of Interaction:
Initially, no ‘username’ cookie exists, so the application displays the ask_name.html form. When you enter a name and submit, a POST request goes to /setcookie. This route extracts the name, creates a redirect response, and uses response.set_cookie() to attach the cookie instructions to that response. The browser receives the redirect and the instruction to store the cookie. On the next request to /, the browser sends the ‘username’ cookie back. The / route reads this cookie using request.cookies.get('username') and displays the show_greeting.html template with the stored name. Clicking ‘Forget My Name’ goes to /clearcookie, which sends back instructions to delete the cookie.
Security Note: Standard cookies are stored in plain text and can be easily viewed and modified by the user or intercepted if not using HTTPS. Never store sensitive information like passwords directly in cookies. For session management, use Flask’s session mechanism, which uses cryptographically signed cookies.