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:
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.
In the Network request list on left select the first request and you will get request details on the right pane.