Python Cookies

But not the kind you eat we’re talking about those little bits of data that websites store on your computer. You know, the ones that remember if you checked a box or added an item to your cart?

Well, in Python land, these are called “cookies” too (because why have different names for things when you can just use one?) and they’re actually pretty easy to work with! Let’s jump right into some code examples.

First off, let’s create a simple Flask app that sets a cookie:

# Importing necessary modules
from flask import Flask, render_template, redirect, request, session

# Creating a Flask app
app = Flask(__name__)

# Defining a route for the home page
@app.route('/')
def home():
    # Checking if 'visits' key exists in the session dictionary
    if 'visits' not in session:
        # If not, set 'visits' to 1
        session['visits'] = 1
    else:
        # If yes, increment 'visits' by 1
        session['visits'] += 1
    # Rendering the template 'index.html' and passing the value of 'visits' to it
    return render_template('index.html', visits=session['visits'])

# Defining a route for resetting the session
@app.route('/reset')
def reset():
    # Deleting the 'visits' key from the session dictionary
    del session['visits']
    # Redirecting to the home page
    return redirect(url_for('home'))

In this code, we’re using Flask to create a basic web app that sets and resets a cookie called “visits”. When you first visit the home page (http://localhost:5000), it will set the initial value of 1 for the visits counter. If you revisit the site, it will increment the count by one each time.

But what’s really happening here is that Flask is using a Python dictionary called “session” to store and retrieve data on your computer (or server). This data is stored as a cookie in your browser, which means it persists even if you close and reopen your web page!

To see this in action, open up your browser’s developer tools (usually accessed by pressing F12) and navigate to the “Application” tab. Then click on “Cookies” to view all of the cookies that are currently set for your site:

As you can see, Flask is setting a cookie called “session” with some random-looking data (which is actually an ID generated by the server). This allows us to keep track of your visits without having to send that information back and forth every time you load a new page!

SICORPS