Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Deleting Cookies

To delete a cookie call set_cookie() method with the name of the cookie and any value
and set the max_age argument to 0. Open main2.py file and add the following code just
after the cookie() view function.

flask_app/main2.py

1 #...
2 @app.route('/delete-cookie/')
3 def delete_cookie():
4 res = make_response("Cookie Removed")
5 res.set_cookie('foo', 'bar', max_age=0)
6 return res
7 #...
Visit http://localhost:5000/delete-cookie/ and you will get the following response:

Now you should have a good understanding of how a cookie works. The following listing
gives you a practical example of how a cookie can be used to store the user preference.

In main2.py add the following code after the delete_cookie() view function.

flask_app/main2.py

1 #...
2 @app.route('/article/', methods=['POST', 'GET'])
3 def article():
4 if request.method == 'POST':
5 print(request.form)
6 res = make_response("")
7 res.set_cookie("font", request.form.get('font'), 60*60*24*15)
8 res.headers['location'] = url_for('article')
9 return res, 302
10
11 return render_template('article.html')
12 #...
Create a new template article.html with the following code:

<!DOCTYPE html>
1 <html lang="en">
2

6
<head>
<meta charset="UTF-8">
7
<title>Article</title>
</head>
8
<body style="{% if request.cookies.get('font') %}font-family:{{
request.cookies.get('font') }}{% endif %}">
9
1
Select Font Preference: <br>
0
<form action="" method="post">
1
<select name="font" onchange="submit()">
1
<option value="">----</option>
1
<option value="consolas" {% if request.cookies.get('font') ==
2
'consolas' %}selected{% endif %}>consolas</option>
1
<option value="arial" {% if request.cookies.get('font') == 'arial'
3
%}selected{% endif %}>arial</option>
1
<option value="verdana" {% if request.cookies.get('font') == 'verdana'
4
%}selected{% endif %}>verdana</option>
1
</select>
5
</form>
1
6
<h1>Festus, superbus toruss diligenter tractare de brevis, dexter olla.</h1>
1
7
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam blanditiis
1
debitis doloribus eos magni minus odit, provident tempora. Expedita fugiat
8
harum in incidunt minus nam nesciunt voluptate. Facilis nesciunt, similique!
1
</p>
9
2
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Alias amet animi
0
aperiam inventore molestiae quos, reiciendis voluptatem. Ab, cum cupiditate
2
fugit illo incidunt ipsa neque quam, qui quidem vel voluptatum.</p>
1
2
</body>
2
</html>
2
3
2
4
2
5
2
6
2
7
The first time user visits http://localhost:5000/article, the page is displayed using the
default browser font. When the user changes the font using the dropdown, we submit

You might also like