Flask-Cookies explained and how to use them?
In this part of the flask tutorial, we are going to learn about cookies in Flask. We are also going to learn why are they essential for any web page and how to implement them in our web page.
Flask – Cookies
A cookie is generally stored in the form of a text file in the client’s machine. The primary purpose of a cookie is to remember and track data of the user regarding the usage of the user for improving the visitor experience and better overall site statistics.
The cookies’ attribute is contained in the request object. It is in dictionary data type and provides all the cookie variables and its values; a client has transmitted in a dictionary object. A cookie also stores the expiry time, path and domain of the site in addition to cookie variables and values.
Cookies in Flask, are set on the response object. We can use the make_response() function to get the response object from the return value of the view function. After getting the response object, we can use the set_cookie() function to store that cookie in a dictionary.
Till now making and storing a cookie is quite a hectic task, but accessing a cookie is comparatively easy. We can use the get() method of request.cookies function to obtain a cookie.
In the following flask application, opening the ‘/’ URL redirects us to a simple form.
@app.route('/') def index(): #renders thr index.html template return render_template('index.html')
The following HTML page contains one input text.
<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>
Then this form is posted to the ‘/setcookie’ URL. Then the userID is set as the name of the cookie and then renders a new 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
Then the ‘readcookie.html’ contains a hyperlink that redirects to another function getcookie(), and then it reads the cookie value and displays the value in the browser.
@app.route('/getcookie') def getcookie(): name = request.cookies.get('userID') return '<h1>welcome '+name+'</h1>'
Now run the above application from python shell and go to the port localhost:5000 to see the magic happening.
I hope you understood the code example and explanation in this tutorial.
Leave a Reply