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 responseRetrieval 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}"
- 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)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
http://localhost:5000/delete-cookie/








