Step-by-Step Guide to Handling Cookies in Flask
First, ensure you have Flask installed. If not, you can install it using pip:
pip install Flask
Create a Flask Application
Here’s a simple Flask application that demonstrates how to set, get, and manage cookies for basic tracking and personalization.
# code
from flask import Flask, request, make_response, render_template
app = Flask(__name__)
@app.route('/')
def index():
user_name = request.cookies.get('username')
if user_name:
greeting = f"Welcome back, {user_name}!"
else:
greeting = "Welcome! Please tell us your name."
return render_template('index.html', greeting=greeting)
@app.route('/setcookie', methods=['POST'])
def setlorookie():
user_name = request.form['name']
resp = make_response(render_template('setcookie.html', name=user_name))
resp.set_cookie('username', user_name, max_age=60*60*24*7) # Cookie expires in one week
return resp
@app.route('/deletecookie')
def deletecookie():
resp = make_response('Cookies cleared. <a href="https://www.w3wiki.net/">Return to Home</a>')
resp.set_cookie('username', '', expires=0)
return resp
if __name__ == '__main__':
app.run(debug=True)
Explanation of the Code
- Index Route (/): This route checks if there is a cookie named ‘username’. If it exists, it greets the user by name; otherwise, it asks for the user’s name.
- Set Cookie Route (/setcookie): This route sets a cookie named ‘username’ when the user submits their name through a form. The cookie is set to expire in one week.
- Delete Cookie Route (/deletecookie): This route allows users to delete their cookie, effectively “forgetting” the user’s name and resetting their experience.
- HTML Templates: You’ll need to create basic HTML templates (index.html and setcookie.html) to facilitate user interaction.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</title>
<body>
<h1>{{ greeting }}</h1>
<form action="/setcookie" method="post">
<input type="text" name="name" placeholder="Enter your name"/>
<button type="submit">Set Cookie</button>
</form>
<a href="/deletecookie">Clear Cookie</a>
</body>
</html>
Output:
Deploying the Flask Project
To run the Flask application, save the script as app.py and run it from your command line:
python app.py
Then, navigate to http://127.0.0.1:5000/ in your browser to interact with the application.
1. Initial Visit
URL: http://127.0.0.1:5000/
Output:
2. Setting the Cookie
URL: http://127.0.0.1:5000/setcookie
Output (GET Request):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Cookie</title>
</head>
<body>
<h1>Set Your Cookie</h1>
<form method="POST" action="/setcookie">
<label for="username">Name:</label>
<input type="text" id="username" name="username">
<button type="submit">Submit</button>
</form>
</body>
</html>
Output:
After submitting the form with your name (e.g., “Monu”)
Form Submission (POST Request):
POST /setcookie HTTP/1.1
Host: 127.0.0.1:5000
Content-Type: application/x-www-form-urlencoded
Content-Length: 14
username=Monu
Response:
A cookie named username is set with the value “Monu”.
You are redirected back to the index page.
3. After Setting the Cookie
URL: http://127.0.0.1:5000/
Output:
Hello, Monu!
Now, the application recognizes the user from the cookie.
This example demonstrates a basic way to manage cookies in a Flask web application, suitable for handling simple user tracking and personalization. For production environments, ensure you implement additional security measures like HTTPS and consider user privacy implications.
Managing Cookies for User Tracking and Personalization in Python
The prevalence of cookies has grown markedly in recent years. Also known as computer cookies, HTTP cookies, web cookies, or internet cookies, they are instrumental in enhancing our online experiences. Created to identify users during website visits, cookies enable sites to track and recognize user devices subsequently. By streamlining web experiences, cookies have become essential tools for marketing and personalization. However, concerns regarding privacy and data security have also emerged. This brief article will offer a history of cookies, a detailed explanation of their intended uses, and an overview of the changing landscape concerning their use.