Flask Cookies – Setting Cookies on Web Applications

Flask Cookies

In this tutorial, we will explore Flask cookies in Python, focusing on how to set cookies in a login web application in Flask. Cookies are small text files stored on the user’s computer, allowing web applications to remember and track data about user activity for better visitor experience.

Introduction to Cookies

Cookies or better, HTTP Cookies are text files, stored on the Client Machine. Each cookie can be stored permanently or for a specific expiration time based on the client’s browser 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.

Also read: Deploy Flask App on VPS

Understanding How 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.

Benefits of Using Cookies

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.

Setting and Retrieving Cookies in Flask

Flask cookies, small text files stored on a client machine, are essential for enhancing user experience and tracking data in web applications. They help servers store and track users’ activities, making it easier to personalize the browsing experience. In Flask, cookies are set on the response object using the make_response() function and retrieved using the request.cookies.get() function. These functions allow developers to easily implement cookies in their Python Flask web applications, improving overall user experience and data tracking.

In a Flask web application, we can set cookies using the make_response() function, which creates a response object. Then, we use the set_cookie() function to attach the cookie to the response object, passing the cookie’s name, value, and expiry time. When a user browses the website, the server sets the cookie, and the client’s browser renders the webpage and saves the cookie.

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. To retrieve cookies in Flask, we use the request.cookies.get() function, which takes the cookie’s name as an argument and returns its value if it exists. The process of setting and retrieving cookies in Flask continues until the cookie expires, after which it is automatically removed from the browser.

Therefore 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)

Creating a Flask Application to Set and Retrieve Cookies

Run the server by executing the Flask application script.

Open your web browser and visit http://localhost:5000/setcookie. This will trigger the setcookie() function, which creates a response with the message “The Cookie has been Set” and sets the ‘Name’ cookie to ‘AskPython’.

Set Cookie
Set Cookie

You should see the message “The Cookie has been Set” displayed in your browser, indicating that the cookie has been successfully set.

Now, visit http://localhost:5000/getcookie. This will trigger the getcookie() function, which retrieves the value of the ‘Name’ cookie and displays it in the format “The Site : {name}”.

Get Cookie
Get Cookie

You should see the message “The Site : AskPython” displayed in your browser, showing that the cookie value has been successfully retrieved.

Conclusion

So there you have it! With this tutorial, we hope you were able to learn more about Flask Cookies and how to implement them in your Python Flask web application. As you may have seen, cookies are an important tool for enhancing user experience and tracking data, and Flask makes it easy to set and retrieve them. Now that you’ve learned how to set and retrieve cookies in Flask, can you think of some other use cases where cookies would improve your web application?