Cookies in Flask

by Alex
Up to this point, all the pages created in the lessons have been very simple. The browser sends a request to the server, the server responds with an HTML page, and that’s it. HTTP is a protocol that doesn’t save its state. This means that HTTP has no built-in way to tell the server that both requests came from the same user. As a result, the server doesn’t know whether the user is trying to access the page for the first time or for the thousandth time. It treats everyone as if it were the first time they accessed the page. If you try to go to any online store and search for certain products, the site will offer recommendations based on the examples of past searches on the next visit. So how is it that the site recognizes a particular user? The answer is cookies and sessions. This lesson is about cookies, and we’ll talk about sessions in the next one.

What are cookies?

A cookie is just a piece of data that a server sets on your browser. Here’s how it works:

  1. The browser sends a request for a web page from the server.
  2. The server responds by sending the requested page along with one or more cookies.
  3. Upon receiving the response, the browser renders the page and stores the cookie on the user’s computer.
  4. A subsequent request to the server will include the cookie information in the cookie header. This will continue until the cookie expires. Once that happens, the cookie is deleted from the browser.

Setting a cookie

Flask uses the set_cookie() method of the response object to set the cookie. The syntax of set_cookie() is as follows:

set_cookie(key, value="", max_age=None)

key – the mandatory argument, this is the name of the cookie. value – the data to be stored in the cookie. By default, it is an empty string. max_age is the lifetime of the cookie in seconds. If you don’t specify the lifetime, it will expire when the user closes the browser. Let’s open main2.py to add the following code after the contact() view function:

from flask import flask, render_template, request, redirect, url_for, flash, make_response
#...
@app.route('/cookie/')
def cookie():
    res = make_response('Setting a cookie')
    res.set_cookie('foo', 'bar', max_age=60*60*24*365*2)
   return res
#...

This is an example of creating a cookie named foo with a bar value, whose expiration date is 2 years. We need to start the server and go to https://localhost:5000/cookie/. As a response the "Setting a cookie" page will open. To see the cookies set by the server, you need to open the repository inspector in Firefox by pressing Shift+F9. A new window will open at the bottom of the browser. On the left side you need to select the storage type “Cookies” and click https://localhost:5000/ to see all the cookies configured by the server for https://localhost:5000/.

Cookies in Flask

From now on, foo cookies will be sent along with the request to the https://localhost:5000/ server. You can verify this by using the network monitor in Firefox. It opens with Ctrl+Shift+E. In the monitor you need to open https://localhost:5000/. In the list of requests on the left side – select the first request, so that the right pane displays its details:Cookies in Flask It’s worth noting that when cookies are configured, subsequent requests to https://localhost:5000/cookie/ will update the cookie term.

Cookie access

The cookie attribute of the request object is used to access the cookie. a cookie is a dictionary type attribute that contains all cookies sent by the browser. Let’s open main2.py again to change the cookie() view function:

#...
@app.route('/cookie/')
def cookie():
   if not request.cookies.get('foo'):
	res = make_response("Setting a cookie")
	res.set_cookie('foo', 'bar', max_age=60*60*24*365*2)
   else:
	res = make_response("Value of cookie foo is {}".format(request.cookies.get('foo')))
   return res
#...
The view function is modified so that the page will show the value of cookies, if there are any. If not, they will be set automatically.

If you open https://localhost:5000/cookie/ now, you will see a page with the following content.Cookies in Flask The request object is also available inside the template. This means that you can access the cookie using Python code as well. We will learn more about this in a later section.

Deleting the cookie

To remove a cookie, you need to call the set_cookie() method with the name of the cookie, any value, and specify a max_age=0 term. In the main2.py file, you can do this by adding the following code after the cookie() view function.

#...
@app.route('/delete-cookie/')
def delete_cookie():
    res = make_response('Cookie Removed')
    res.set_cookie('foo', 'bar', max_age=0)
   return res
#...

If you go to https://localhost:5000/delete-cookie/ now , the following response will be displayed: Cookies in Flask Now that you understand how cookies work, you can explore the following code examples and get real-world, practical examples of how to set up cookies to preserve user preferences. Let’s add the following code after the delete_cookie() view function in main2.py.

#...
@app.route('/article/', methods=['POST', ' GET'])
def article():
   if request.method == 'POST':
	print(request.form)
	res = make_response(")
	res.set_cookie("font", request.form.get('font'), 60*60*24*15)
	res.headers['location'] = url_for('article')
	return res, 302

   return render_template('article.html')
#...

Next you need to create a new article.html template with the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Article</title>
</head>
<body style="{% if request.cookies.get('font') %}font-family:{{ request.cookies.get('font') }}{% endif %}">

Select Font Preference <br>
<form action="" method="post">
    <select name="font" onchange="submit()">
	<option value="">----</option>
	<option value="consolas" {% if request.cookies.get('font') == 'consolas' %}selected{% endif %}>consolas</option>
	<option value="arial" {% if request.cookies.get('font') == 'arial' %}selected{% endif %}>arial</option>
	<option value="verdana" {% if request.cookies.get('font')== 'verdana' %}selected{% endif %}>verdana</option>
    </select>
</form>

<h1>Festus, superbus toruss diligenter tractare de brevis, dexter olla.</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam blanditiis debitis doloribus eos magni minus odit, provident tempora. Expedita fugiat harum in incidunt minus nam nesciunt voluptate. Facilis nesciunt, similique!
</p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias amet animi aperiam inventore molestiae quos, reiciendis voluptatem. Ab, cum cupiditate fugit illo incidunt ipsa neque quam, qui quidem vel voluptatum.</p>


</body>
</html>

When the user visits https://localhost:5000/article for the first time, the page will display with the default font. If the user changes the font using the drop-down menu, the form will be sent. The value of the condition if request.method == 'POST' will become true and a font cookie with the value of the selected font will be set, which will expire after 15 days, and the user will be redirected to https://localhost:5000/article, which will be displayed with the new selected font. When the user visits https://localhost:5000/article the page will be displayed with the default font.Cookies in Flask But if you select a new font from the dropdown menu, the page font will change to the one you selected earlier. Cookies in Flask Disadvantages of cookies Before using cookies in a real project, you need to know about their disadvantages.

  1. Cookies are not secure. The data they store is visible to everyone, so you can’t store passwords, bank card data, and so on in cookies.
  2. Cookies can be turned off. Most browsers give users the option to disable cookies. If this happens, there is no warning. To combat this problem, you can use, for example, this simple JS code to notify the user that cookies must be enabled to work properly.
<script>
    document.cookie = "foo=bar;";
    if (!document.cookie)
    {
	alert("This website requires cookies to function properly");
    }
</script>
  1. Each batch of cookies stores no more than 4 KB of data. In addition, browsers impose limits on how many cookies a site can set. Limits range from 30 to 50.
  2. Cookies are sent with each request to the server. Assuming the site has 20 cookies of 4KB, each request would result in an additional load of 80KB.

Some of these problems can be solved with the help of sessions, which will be discussed in the next lesson.

Related Posts

LEAVE A COMMENT