Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
wb_sunny

Flask Cookies – Setting Cookies on Web Applications

Flask Cookies

In this tutorial, we will deal with Flask cookies and use them in the Flask Web Application. So buckle up, and let’s get started.

What are Cookies?

Cookies or better, HTTP Cookies are text files, stored on the Client Machine. Each cookie can be stored permanently or for a specific expiry time based on the Client Browser’s cookie settings.

After the Cookie reaches its expiry date and time, it is automatically removed from the Client Browser.

Cookies present on the Client-side tracks and remember the user’s activity on the web. This information is later used to improve the user’s overall Site experience.

How do cookies work?

As we know, HTTP is a stateless protocol, which means that the server can’t distinguish whether a user is visiting the site for the first time or not. So to solve this problem, sites use cookies.

Therefore, when a Client visits a particular site for the first time, the client will not have any cookies set by the site. So the server creates a new cookie and sends it to the Client machine itself.

So in the next subsequent visits, the client machine will attach the cookie to the request and send it. The server then retrieves the cookies from the request object and uses that cookie information to improve the site’s user experience.

Why are cookies used?

In a nutshell, We use cookies to provide a better user experience on the site by storing and tracking the user’s activity. Also, they store information such as the expiry date, path, and domain of the site.

Some of the places where Cookies play its role are:

  • You might have noticed in eCommerce or social media websites like Facebook that when you leave the site without logging out, your account is still logged in the next time you visit the site.
  • In many eCommerce websites, you get recommendations about different products based on your browser’s previous search information.

All this is done using cookies.

Hands-On with setting Flask Cookies

In Flask, Cookies are set on the response object. That is, the server sends the Cookie to the user along with the response.

We do it using the make_response() function. Once the response is set, we use the set_cookie() function to attach the cookie to it.

The cookie takes the attributes:

response.set_cookie('<Title>','<Value>','<Expiry Time>')

Therefore, the code looks like:

@app.route('/setcookie')
def setcookie():
    resp = make_response(f"The Cookie has been set")
    resp.set_cookie('Name','AskPython')
    return resp

Simple right! Now we need to get the Cookie back from the user. The cookie is sent back along with the Request to the server. We Retrieve it using the request.cookies.get() function.

Therfore consider the Code:

@app.route('/getcookie')
def getcookie():
    name = request.cookies.get('Name', None)
    return f"The Site : {name}"

Here the Cookie information is stored in the name variable.

Therefore the Final Main Application File will be:

from flask import Flask, make_response, request

app = Flask(__name__)

@app.route('/setcookie')
def setcookie():
    resp = make_response(f"The Cookie has been Set")
    resp.set_cookie('Name','AskPython')
    return resp

@app.route('/getcookie')
def getcookie():
    name = request.cookies.get('Name')
    return f"The Site : {name}"

app.run(host='localhost', port=5000)

Implementation of the Code

Let us now run the server and go to “/setcookie

Set Cookie
Set Cookie

And to “/getcookie

Get Cookie
Get Cookie

Perfect!

Conclusion

That’s it, guys. This was all about Flask Cookies. Do try out the code on your own for better understanding.

See you guys in the next time!