Flask Cookies
The cookies are stored in the form of text files on the client’s machine. Cookies are used to track the user’s activities on the web and reflect some suggestions according to the user’s choices to enhance the user’s experience.
Cookies are set by the server on the client’s machine which will be associated with the client’s request to that particular server in all future transactions until the lifetime of the cookie expires or it is deleted by the specific web page on the server.
In flask, the cookies are associated with the Request object as the dictionary object of all the cookie variables and their values transmitted by the client. Flask facilitates us to specify the expiry time, path, and the domain name of the website.
In Flask, the cookies are set on the response object by using the set_cookie() method on the response object. The response object can be formed by using the make_response() method in the view function.
In addition, we can read the cookies stored on the client’s machine using the get() method of the cookies attribute associated with the Request object.
A simple example to set a cookie with the title ‘foo’ and the content ‘bar’ is given below.
Example
The above python script can be used to set the cookie with the name ‘foo’ and the content ‘bar’ on the browser for the website localhost:5000.
Run this python script using the command python script.py and check the result on the browser.
We can track the cookie details in the content settings of the browser as given in below image.
Login application in Flask
Here, we will create a login application in the flask where a login page (login.html) is shown to the user which prompts to enter the email and password. If the password is “jtp”, then the application will redirect the user to the success page (success.html) where the message and a link to the profile (profile.html) is given otherwise it will redirect the user to the error page.
The controller python flask script (login.py) controls the behaviour of the application. It contains the view functions for the various cases. The email of the user is stored on the browser in the form of the cookie. If the password entered by the user is “jtp”, then the application stores the email id of the user on the browser as the cookie which is later read in the profile page to show some message to the user.
The application contains the following python and HTML script. The directory structure of the application is given below.
login.py
login.html
success.html
profile.html
Execution
Run the python script by using the command python login.py and visit localhost:5000/ on the browser as given in the following snapshots.
Click Submit. It will show the success message and provide a link to the profile.html.
Click on view profile. It will read the cookie set as a response from the browser and display the following message.