No, not the delicious kind you eat for breakfast (although those are pretty great too). We’re talking about HTTP cookies, which are small text files stored on a user’s device when they visit a website.
Now, if you’ve ever wondered how websites remember your login information or preferences, it’s because of these little guys! And guess what? You can customize the cookie policy for your Python web application too!
To kick things off let’s create a simple Flask app that sets and reads cookies. Here’s some code to get you started:
# This script is for creating a simple Flask app that sets and reads cookies.
# Importing necessary modules
from flask import Flask, render_template, request, redirect, session
# Creating an instance of Flask
app = Flask(__name__)
# Defining the home route
@app.route('/')
def home():
# Checking if 'username' key is present in the session dictionary
if 'username' in session:
# If present, return a welcome message with the username
return "Welcome back, {}!".format(session['username'])
else:
# If not present, render the index.html template
return render_template('index.html')
# Defining the login route
@app.route('/login', methods=['GET', 'POST'])
def login():
# Checking the request method
if request.method == 'POST':
# If the method is POST, get the username from the form and store it in a variable
username = request.form['username']
# Add the username to the session dictionary
session['username'] = username
# Redirect to the home route
return redirect(url_for('home'))
else:
# If the method is GET, render the login.html template
return render_template('login.html')
# Defining the logout route
@app.route('/logout')
def logout():
# Removing the 'username' key from the session dictionary
session.pop('username', None)
# Redirect to the home route
return redirect(url_for('home'))
In this example, we’re using Flask sessions to store the username in a cookie when the user logs in. When they visit the home page again, their name will be displayed based on what was stored in the session. Pretty cool, right?
But wait there’s more! You can also customize your cookie policy by setting various options like expiration time and domain restrictions. Here’s an example of how to do that:
# Import necessary modules
from flask import Flask, render_template, request, redirect, session
import datetime
# Create Flask app instance
app = Flask(__name__)
# Define route for home page
@app.route('/')
def home():
# Check if 'username' key exists in session
if 'username' in session:
# If yes, display personalized welcome message
return "Welcome back, {}!".format(session['username'])
else:
# If no, render index.html template
return render_template('index.html')
# Define route for login page
@app.route('/login', methods=['GET', 'POST'])
def login():
# Check request method
if request.method == 'POST':
# If POST, get username from form data
username = request.form['username']
# Store username in session
session['username'] = username
# Create redirect response to home page
response = redirect(url_for('home'))
# Set cookie options
response.set_cookie('my-cookie', value='hello world', expires=datetime.timedelta(days=30), httponly=True)
return response
else:
# If GET, render login.html template
return render_template('login.html')
# Define route for logout
@app.route('/logout')
def logout():
# Remove 'username' key from session
session.pop('username', None)
# Create redirect response to home page
response = redirect(url_for('home'))
# Delete cookie by setting expiration date to past
response.set_cookie('my-cookie', '', expires=datetime.timedelta(days=-1))
return response
In this example, we’re setting the `expires` option to 30 days and adding an `httponly` flag to prevent client-side scripting from accessing the cookie value (which is a security measure). And when the user logs out, we’re deleting the cookie by setting its expiration time to -1.
Customized cookie policy in Python made easy.