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
Create cookie
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 |
|
This HTML page contains a text input.
1 | <html> |
Set cookie
The form is published to the ‘/setcookie’ URL.The associated view function sets the cookie name userID and renders another page.
1 |
|
Get cookie
‘readcookie.html’ contains a hyperlink to another view function getcookie (), which reads back and displays the cookie value in the browser.
1 |
|
Run the app and access localhost:5000/
After you click login, the cookie is set and you can read the cookie.
Related course: Python Flask: Create Web Apps with Flask