Cookies are stored on the client’s computer as text files.The aim is to remember and track data that is relevant to customer usage for better visitor experience and website statistics.

The Flask Request object contains the properties of the cookie.It is a dictionary object for all cookie variables and their corresponding values, and the client is transferred.In addition to this, cookies also store the expiration time, path, and domain name of its website.

Related course: Python Flask: Create Web Apps with Flask

Flask cookies

In Flask, set the cookie on the response object.Use the make_response() function to get the response object from the return value of the view function.After that, the cookie is stored using the set_cookie() function of the response object.

It is easy to read back cookies.The get() method of the request.cookies property is used to read the cookie.

In the following Flask application, when you access the ‘ /‘ URL, a simple form opens.

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

This HTML page contains a text input.

1
2
3
4
5
6
7
8
9
10
11
<html>
<body>

<form action = "/setcookie" method = "POST">
<p><h3>Enter userID</h3></p>
<p><input type = 'text' name = 'nm'/></p>
<p><input type = 'submit' value = 'Login'/></p>
</form>

</body>
</html>

The form is published to the ‘/setcookie’ URL.The associated view function sets the cookie name userID and renders another page.

1
2
3
4
5
6
7
8
9
@app.route('/setcookie', methods = ['POST', 'GET'])
def setcookie():
if request.method == 'POST':
user = request.form['nm']

resp = make_response(render_template('readcookie.html'))
resp.set_cookie('userID', user)

return resp

‘readcookie.html’ contains a hyperlink to another view function getcookie (), which reads back and displays the cookie value in the browser.

1
2
3
4
@app.route('/getcookie')
def getcookie():
name = request.cookies.get('userID')
return '<h1>welcome ' + name + '</h1>'

Run the app and access localhost:5000/

flask set cookie

After you click login, the cookie is set and you can read the cookie.

Related course: Python Flask: Create Web Apps with Flask