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.

Python
# 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="/">Return to Home</a>')
    resp.set_cookie('username', '', expires=0)
    return resp

if __name__ == '__main__':
    app.run(debug=True)

Explanation of the Code

  1. 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.
  2. 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.
  3. Delete Cookie Route (/deletecookie): This route allows users to delete their cookie, effectively ā€œforgettingā€ the userā€™s name and resetting their experience.
  4. HTML Templates: Youā€™ll need to create basic HTML templates (index.html and setcookie.html) to facilitate user interaction.

index.html

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):

HTML
<!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.

Similar Reads

Exploring HTTP Cookies: Their Functions and Advantages

When you visit a website, you may see a banner or pop-up asking about your cookie choices. HTTP cookies, which are designed specifically for internet web browsers, help track, personalize, and save session information. They are short text files that assist users in identifying their computers while navigating a computer network. When you visit a website for the first time, a cookie is stored in your browserā€™s files with the URL, a unique generated number, and an expiration date. As you navigate the site, each new page requests the cookie, allowing the website to tailor your experience depending on your browsing history....

Types of Cookies

Cookies are classified according to their attributes, such as source, duration, and purpose....

Step-by-Step Guide to Handling Cookies in Flask

First, ensure you have Flask installed. If not, you can install it using pip:...

Conclusion

Cookies have become a fundamental part of our digital experiences, improving customization and facilitating web interactions. They have grown from simple user tracking tokens to complex analytics, advertising, and session management capabilities. While privacy concerns have caused improvements in cookie rules and browser functionality, the digital industry is actively looking for ways to protect user privacy while still providing a personalized online experience. As we enter a cookieless future, new technologies and regulations will impact how data is collected, shared, and used, guaranteeing a balance between user privacy and digital innovation....