Python Flask-Set cookie

Flask-Cookies

A cookie is stored in the client's computer in the form of a text file. It just a piece of data that the server sets in the browser.
The browser sends the request for a webpage to the server. The server responds to the browser request by sending the requested webpage along with one or more cookies.
By receiving upon the response, the browser renders the webpage and saves the cookie on the user computer.
The subsequent request to the server will include data from all the cookies in the Cookie header. This process will continue until the cookie expires and it is removed from the browser.

To Set a cookie

In Flask, we use the set_cookie() method of the response object to set cookies. The syntax of the set_cookie() method is as follows:
set_cookie(key, value="", max_age=None)
A key is a required argument and it refers to the name of the cookie. The value is data that you want to store in the cookie and it defaults to empty string. The max_age refers to the expiration time of the cookie in seconds, the cookie will cease to exist when the user closes the browser if not set.
Open main2.py and add the following code just after the contact() view function:

flask_app/main2.py

from flask import Flask, render_template, request, redirect, url_for, flash, make_response
@app.route('/cookie/')
def cookie():
    res = make_response("Setting a cookie")
    res.set_cookie('spark', 'bar', max_age=60*60*24*365*2)
    return res
Here we are creating a cookie named spark with the value bar that will last for 2 years.

Start the server and visit http://localhost:5000/cookie/. We should see a page with "Setting a cookie" as a response. A new window will appear at the bottom of the browser window. On the left side, select the “Cookies” storage type and then click on http://localhost:5000/ to view all cookies set by the server at http://localhost:5000/.
From now onwards, the cookie spark will be sent along with any request to the server at http://localhost:5000/.Open Network Monitor and visit http://localhost:5000/.
In the Network request list on left select the first request and you will get request details on the right pane.
Note that once the cookie is set the subsequent requests to http://localhost:5000/cookie/ will update the expiration time of the cookie.