English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask Cookie Handling

Cookies are stored in the form of text files on the client computer. The purpose is to remember and track data related to customer use to provide a better access experience and website statistics.

The Request object contains a cookie attribute. It is a dictionary object of all cookie variables and their corresponding values sent by the client. In addition, the cookie will also store its expiration time, path, and domain name of the site.

In Flask, cookies are set on the response object. Use the make_response() function to obtain the response object from the return value of the view function. Then, use the set_cookie() function of the response object to store the cookie.

It is easy to reread cookies. You can use the get() method of the request.cookies attribute to read cookies.

In the following Flask application, when accessing URL => / When this occurs, a simple form will open.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
@app.route('/)
 def index():
     return render_template('index.html')

This HTML page contains a text input, the complete code is shown as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Cookies Example</title>
 </head>
    <body>
       <form action="/setcookie" method="POST">
          <p><h3>Enter userID</h3></p>
          <p><input type='text' name='name'>/></p>
          <p><input type='submit' value='Login'>/></p>
       </form>
    </body>
 </html>

Form submitted to URL => /setcookie. The associated view function sets a cookie named: userID, and presents it on another page.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
@app.route('/setcookie', methods=['POST', 'GET'])
 def setcookie():
    if request.method == 'POST':
         user = request.form['name']
         resp = make_response(render_template('readcookie.html'))
         resp.set_cookie('userID', user)
         return resp

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

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
@app.route('/getcookie)
 def getcookie():
     name = request.cookies.get('userID')
     return '<h1>welcome '+name+"/h1"

The complete application code is as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask
 from flask import render_template
 from flask import request
 from flask import make_response
 app = Flask(__name__)
 @app.route('/)
 def index():
     return render_template('index.html')
 @app.route('/setcookie', methods=['POST', 'GET'])
 def setcookie():
     if request.method == 'POST':
         user = request.form['name']
         resp = make_response(render_template('readcookie.html'))
         resp.set_cookie('userID', user)
         return resp
 @app.route('/getcookie)
 def getcookie():
     name = request.cookies.get('userID')
     print (name)
     return '<h1>welcome,+name+"/h1"
 if __name__ == '__main__':
     app.run(debug=True)

Run the application and access the URL => http://localhost:5000/The result of setting the cookie is as follows -

The output of reading the cookie is as follows -