Flask – Cookies

A cookie is put away on a customer's PC as a form of text file. Its purpose is to recollect and track information relating to a customer's use for better visitor experience and site statistics.

A Request object contains a cookie's property. It is a word reference object of all the cookie factors and their corresponding values, a customer has transmitted. Notwithstanding it, a cookie additionally stores its expiry time, path and domain name of the site.

In Flask, cookies are determined to reaction object. Use make_response() capacity to get reaction object from return estimation of a view work. From that point onward, utilize the set_cookie() capacity of response object to store a cookie.

Reading back a cookie is simple. The get() strategy for request.cookies attribute is utilized to read a cookie.

In the accompanying Flask application, a simple structure opens up as you visit '/' URL.

def index():
   return render_template('index.html')

This HTML page contains one text input.

      <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>

The Form is posted to ‘/setcookie’ URL. The associated view function sets a Cookie name userID and renders another page.

@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 browser.
def getcookie():
   name = request.cookies.get('userID')
   return '<h1>welcome '+name+'</h1>'

Run the application and visit http://localhost:5000/

The result of setting a cookie is displayed like this −