Table of contents
1.
Introduction
1.1.
What is a cookie
2.
Cookies in Flask
2.1.
Request Object
2.2.
Setting cookies in Flask
2.3.
Retrieval of cookies in Flask
2.4.
Deletion of cookies in Flask
3.
Example 
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024

Handling Cookies in Flask

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Do you watch Netflix or shop at Amazon, or have you ever logged into some website with the "remember me" button checked? Have you ever wondered how these sites show you the recommendations or save your personal information for recommending products based upon your search? To store the personalized info of every user in a database is troublesome and time-consuming. For this purpose, we keep a site's cookies in the user's browser. 

What is a cookie

Cookies are files that websites save on your computer or mobile device when visiting a website. The cookies store information about our visit to improve how it works and provide services tailored to our interests. Cookies can also be used to store user preferences, such as your language or region preferences. Cookies provide several benefits to users, including improving the user experience, increasing website and web application performance, and helping the website recognize repeat visitors.

Now let us discuss how these cookies can be stored and accessed in a flask application. We will also go through an example to add a cookie for our flask application.

Cookies in Flask

Flask uses built-in cookie functionality to store session cookies and make them available to our views. This allows us to build features that require the ability to remember the state of a user between browser sessions, such as the ability to remember a user's preferences or logout state. But before discussing cookies in Flask, we have to highlight some essential features to handle cookies in Flask.

Request Object

A request object is a powerful tool that can make all sorts of advanced web requests. It provides a convenient wrapper for accessing the request object provided by the flask object. This object represents the current HTTP request made by the user's browser

The request object has several attributes that can be accessed and manipulated in our code. We can use the request.forms, request.cgi, and other request attributes just as if they were properties of Flask.request. One of those attributes is cookies which contains a dictionary of cookie names as keys and their value representing cookie value. A cookie also stores its expiry time, path, and URL of the site.

Setting cookies in Flask

Cookies are set on the response object in Flask. First, we initialize a response object with make_response() and then attach the cookie key: value pair to this object with the help of the set_cookie() command. 

In the following example, we see UserId as the cookie attached to the response object with the value 21.

from flask import Flask, make_response

app = Flask(__name__)
@app.route('/setCookie', methods = ['POST', 'GET'])

def setCookie():
    response = make_response() # We can also render new page with render_template
    response.set_cookie('UserId',21)
    return response
You can also try this code with Online Python Compiler
Run Code

Retrieval of cookies in Flask

Let us have a look at how can we retrieve the same cookie data from the request object:

  • We can display it directly 
from flask import Flask, request

app = Flask(__name__)
@app.route('/getCookie', methods = ['POST', 'GET'])
def getCookie():
    userId = request.cookies.get('UserId')
    return f"Welcome user id: {userId}"
You can also try this code with Online Python Compiler
Run Code

 

  • We can pass the data for rendering on another page
from flask import Flask, request

app = Flask(__name__)
@app.route('/getCookie', methods = ['POST', 'GET'])
def getCookie():
    userId = request.cookies.get('UserId')
    return render_template('showCookies.html', id = userId)
You can also try this code with Online Python Compiler
Run Code

Deletion of cookies in Flask

We can also delete cookies. Let’s look at an example to understand this better.

Set the max_age parameter to 0 in set cookie() with the name of the cookie and any value to erase it. Add the following code directly after the cookie() view method in the app.py file.

app.py

@app.route('/delete-cookie/')
def delete_cookie():
    res = make_response("Cookie Removed")
    res.set_cookie('foo', 'bar', max_age=0)
    return res
You can also try this code with Online Python Compiler
Run Code

 

http://localhost:5000/delete-cookie/

Example 

Here’s how whole cookie formation, sending, and retrieval can be done all together in one application:

app.py

@app.route('/')
def home():
    return render_template('home.html')
You can also try this code with Online Python Compiler
Run Code

 

Home.html

<html>
   <body>
   
      <form action = "/setcookie" method = "POST">
         <p><h3>Enter your username</h3></p>
         <p><input type = 'text' name = 'username'/></p>
         <p><input type = 'submit' value = 'Login'/></p>
      </form>
     
   </body>
</html>

 

Output:

 

On submitting the form, it’ll route to /setcookies in flask which is:

app.py

@app.route('/setcookie')
def setcookie():
    user_name = request.form['username']
    resp = make_response(render_template('retrieveCookie.html'))
    resp.set_cookie('user_name',user_name)
    return resp
You can also try this code with Online Python Compiler
Run Code

 

setCookie()  will make a response object with the attached cookie attribute and render the retrieveCookie.html, which contains a hyperlink to fetch the cookie just sent.

On Clicking the hyperlink, which redirects to /getCookie, will trigger the following Flask 

function:

 

app.py

@app.route('/getcookie')
def getcookie():
    name = request.cookies.get('user_name')
    return f"Welcome {name}"
You can also try this code with Online Python Compiler
Run Code

 

The output of the fetched cookie function will be :

 

And this is how cookie handling is done in the flask. 

Recommended Topic, PHP For Loop

FAQs

1. Do cookies in Flask expire automatically?
Cookies' expiration date depends on the browser's cookie settings. The cookies without an expiry time expire when the browser is closed. We can renew a cookie in Flask with the @before_request handler.
 

2. Should we store cookies in the database?
Generally, we should not store cookie data in any database because it is highly volatile, which is better kept in the user's browser storage for faster retrieval.
 

3. How can we check if a cookie is present or not in a flask application?
We can check if the key is present in the cookie attribute of the request object by the following code:

from flask import request

if 'country' in request.cookies:
    # Do something
else:
# Do something else
You can also try this code with Online Python Compiler
Run Code


4. Does Flask support secure cookies?
Flask does support secure cookies. We can set a cookie to be secured by adding the secure parameter in set_cookie() as true.

response.set_cookie('name', 'World', secure=True)
You can also try this code with Online Python Compiler
Run Code


5. What is the secret key in Flask?
Each Flask web application has a secret key used to sign session cookies and secure them from being tampered. An attacker mustn't know how much this private key is worth.

Key Takeaways

With this article, you all ninjas have learned how flask cookies can be set, retrieved, and deleted as per the requirement. We have seen a whole cookie process that shows how a flask application handles cookies.

For more flask-related information and solve your queries, head over to Flask Introduction and Overview. Also, see Form data in Flaskflask request object, and app routing in Flask in detail by our official blog site Coding Ninjas Studio.

Live masterclass