Python Flask-Access Cookie

To Access Cookies

To access the cookie, we use the cookie attribute of the request object. A dictionary-like attribute that contains all the cookies sent by the browser is known as the cookie attribute. Open main2.py and modify the cookie() view function as follows:

@app.route('/cookie/')
def cookie():
    if not request.cookies.get('spark'):
        res = make_response("Setting a cookie")
        res.set_cookie('spark', 'bar', max_age=60*60*24*365*2)
    else:
        res = make_response("Value of spark is {}".format(request.cookies.get('spark')))
    return res
We have to modify our view function to display the cookie value assuming there is a cookie. Otherwise, it will set a cookie for us.
Visit http://localhost:5000/cookie/ to view the following response. Inside the template, A request object is also available. By using the same way as in Python code we can access the cookies, inside the template.