Skip to main content

Get and set cookies with Flask

In this blog post, we'll walk you through the process of getting and setting cookies in a Flask application with step-by-step examples. Cookies are small pieces of data stored on the client-side and are essential for managing user sessions and preferences in web applications. Flask, a lightweight WSGI web application framework in Python, provides simple methods to work with cookies.

 

 

Get and set cookies with Flask

 


Setting Up Your Flask Environment


Before we dive into cookies, ensure you have Flask installed. 

 

pip install Flask


Next, create a basic Flask application. Create a new file called `app.py` and add the following code:
 
 


from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

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

Run the application by executing:

python app.py


Your Flask app should now be running on `http://127.0.0.1:5000/`.

 

Read also:
 

 


 

Setting Cookies


To set a cookie in Flask, you need to create a response object and use its `set_cookie` method. Here's how you can do it:

 

Create a route to set a cookie

 


 @app.route('/setcookie')
   def set_cookie():
       response = make_response('Cookie is set')
       response.set_cookie('username', 'daily aspirants')
       return response

In this example, we define a route `/setcookie` which sets a cookie named `username` with the value `daily aspirants`. The `make_response` function creates a response object, and `set_cookie` sets the cookie.

Test setting the cookie

 
Navigate to `http://127.0.0.1:5000/setcookie` in your browser. You should see "Cookie is set" displayed, and the `username` cookie will be stored in your browser.

 

Getting Cookies


Retrieving cookies is straightforward with Flask. You can access cookies using the `request` object's `cookies` attribute.

 

Create a route to get the cookie


   @app.route('/getcookie')
   def get_cookie():
       username = request.cookies.get('username')
       if username:
           return f'Username stored in cookie is {username}'
       else:
           return 'No username cookie found'

This route, `/getcookie`, tries to retrieve the `username` cookie. If it exists, it returns the value; otherwise, it informs the user that no cookie was found.
 

Test getting the cookie:

 
Navigate to `http://127.0.0.1:5000/getcookie` in your browser. If the cookie was set previously, you should see "Username stored in cookie is daily aspirants". If not, you will see "No username cookie found". 

Deleting Cookies


Sometimes, you might need to delete a cookie. You can achieve this by setting the cookie's expiration date to a time in the past.

Create a route to delete the cookie





@app.route('/deletecookie')
   def delete_cookie():
       response = make_response('Cookie has been deleted')
       response.set_cookie('username', '', expires=0)
       return response

In this example, the `/deletecookie` route sets the `username` cookie's expiration date to `0`, effectively deleting it.
 

Test deleting the cookie:

 
 
Navigate to `http://127.0.0.1:5000/deletecookie` in your browser. You should see "Cookie has been deleted". Now, if you navigate back to `http://127.0.0.1:5000/getcookie`, you will see "No username cookie found".
 
 

Here's a summary of the code we used:

 
 

 

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

@app.route('/setcookie')
def set_cookie():
    response = make_response('Cookie is set')
    response.set_cookie('username', 'daily aspirants')
    return response

@app.route('/getcookie')
def get_cookie():
    username = request.cookies.get('username')
    if username:
        return f'Username stored in cookie is {username}'
    else:
        return 'No username cookie found'

@app.route('/deletecookie')
def delete_cookie():
    response = make_response('Cookie has been deleted')
    response.set_cookie('username', '', expires=0)
    return response

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


Now, create a `templates` directory and add the following HTML files for the respective routes:

 

'templates/index.html'

 



<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Flask Cookie Demo</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <h1>Welcome to the Flask Cookie Demo</h1>
      <p>
        {% if request.cookies.get('username') %}
          Hello, {{ request.cookies.get('username') }}! <a href="{{ url_for('logout') }}" class="btn btn-primary">Logout</a>
        {% else %}
          You are not logged in. <a href="{{ url_for('login') }}" class="btn btn-primary">Login</a>
        {% endif %}
      </p>
    </div>
  </body>
</html>


Get and set cookies with Flask

 

'templates/login.html'


 


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Login</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <h1>Login</h1>
      <form method="post">
        <div class="form-group">
          <label for="username">Username</label>
          <input type="text" class="form-control" id="username" name="username" required>
        </div>
        <button type="submit" class="btn btn-primary">Login</button>
      </form>
    </div>
  </body>
</html>


 

 
Get and set cookies with Flask

templates/readcookies.html

 


 

 


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Read Cookies</title>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div class="container mt-5">
      <h1>Read Cookies</h1>
      <p>
        {% if username %}
          Username stored in cookie is {{ username }}.
        {% else %}
          No username cookie found.
        {% endif %}
      </p>
      <a href="{{ url_for('index') }}" class="btn btn-primary">Back to Home</a>
    </div>
  </body>
</html>

Get and set cookies with Flask

 


app.py


from flask import Flask, request, make_response, render_template, redirect, url_for

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        response = make_response(redirect(url_for('index')))
        response.set_cookie('username', username)
        return response
    return render_template('login.html')

@app.route('/logout')
def logout():
    response = make_response(redirect(url_for('index')))
    response.set_cookie('username', '', expires=0)
    return response

@app.route('/readcookies')
def read_cookies():
    username = request.cookies.get('username')
    return render_template('readcookies.html', username=username)

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

 

Conclusion


In this tutorial, we've covered the basics of setting, getting, and deleting cookies in a Flask application. Cookies are crucial for maintaining state and personalizing user experiences. By leveraging Flask's simple and intuitive methods, you can effectively manage cookies in your web applications.

Comments

Popular posts from this blog

Contact Management System project using C with source code

Contact Management System (CMS)   A Contact Management System (CMS) is an essential application for organizing and managing contacts efficiently. Here's a simple implementation of a Contact Management System using C, allows users to perform operations such as adding, viewing, searching, modifying, and deleting contacts through a simple and user-friendly console interface. The CMS provides a practical demonstration of fundamental programming concepts such as arrays, structures, and string manipulation, making it an excellent project for students and beginners in C programming.   Project Overview The Contact Management System is designed to store basic information about contacts, including: Name: name of the person. Phone Number: phone number of the contact. Email Address: email address of the contact.   With this information, the program offers the following functionalities: Add New Contact...

Implementing Basic Add to Cart Functionality in Python Using Flask

In e-commerce websites, the "Add to Cart" feature allows users to select products they want to purchase and store them temporarily while they continue shopping. Implementing this functionality in a web application using Python and Flask is straightforward and can be done with a few simple steps.       Setting Up the Project: First, create a new directory for your project and set up a virtual environment to manage dependencies. Install Flask using pip and create three main files: `app.py`, `index.html`, and `cart.html`.   Read also:   Unlocking the Power of Free Google Tools for Seo Success Ultimate Guide: Google Search Console Crawl Reports you need to know Monitor What is dofollow backlinks: The ultimate 5 Benefit for your websites SEO Schema markup and How can you use schema markup for seo      Creating HTML Templates: Create HTML templates for displaying products (`index.html`) and the shopping cart (`cart.html`). These templates will use ...

Advanced HTML Concepts: Techniques and Examples for Modern Web Development

Advanced HTML goes beyond the basics of creating simple web pages, delving into powerful features and techniques that improve web interactivity, accessibility, and performance. It includes concepts such as semantic HTML, custom data attributes, responsive images with <picture> , enhanced forms, interactive content using <details> and <summary> , and embedding external resources with <iframe> .          Furthermore, advanced HTML focuses on SEO optimization through meta tags, accessibility improvements using ARIA, creating reusable Web Components, and optimizing performance with async and defer scripts.    Semantic HTML   Semantic elements clearly describe their meaning in a human- and machine-readable way.   <header> <h1>Welcome to My Website</h1> </header> <nav> <ul> <li><a href="home">Home...

Python Flask Student List CRUD System Using MySQL Database for Beginners

  In this tutorial, we are going to learn the python flask student list crud system using MySQL database for beginners. Before you have to learn how to python flask setting up and connect MySQL database connection and templates uses.    Read also: Python Flask tutorial Setting up a Flask and Sql Database on the create project folder you have to install two things to fetch data and flask. Here, below code to install using python terminal, and for MySQL, am using xampp software and database inside environment to turn on the apache server and MySQL database.   Read also: Python Flask with Mysql Database Import Flask and MySQL: from flask import Flask, render_template, request, redirect, url_for from flask_mysqldb import MySQL MySQL Database Connection: app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] ...

Microdata Schema : How can Microdata schema Improve SEO with Examples

In this article, we will explore what microdata schema is, how it works, and provide some examples to help you better understand its importance. What is Microdata Schema? Microdata schema is a markup language that provides a standardized way of adding structured data to web pages. It uses HTML tags to describe information about the content on a web page, such as product reviews, events, recipes, and more. This makes it easier for search engines to crawl and index the content on a web page, which can help improve the visibility and ranking of the website. How Does Microdata Schema Work? Microdata schema uses a set of properties and item types to describe the content on a web page. Properties describe specific attributes of an item, while item types describe the type of item being described. For example, the property "name" might be used to describe the name of a person, while the item type "Person" would be used to indicate that the content being describ...

How to Create a Personal details information program in HTML

In this tutorial, we are learning how you can create a personal details information program in HTML with the simple using of HTML tags. HTML Form: <div class="container"> <h1 style="text-align:center">Personal Details</h1> <form class="form-control"> <label for="name">Name:</label><br> <input type="text" id="name" name="name"><br> <label for="email">Email:</label><br> <input type="email" id="email" name="email"><br> <label for="dob">Date of Birth:</label><br> <input type="date" id="dob" name="dob"><br> <label for="gender">Gender:</label><br> <input type="radio" id="gender" name="gender" value="male...