Python Flask Cookies

Master programming with our job-ready courses: Enroll Now

In web development, cookies are small pieces of data that are stored on a user’s device by a website. They are widely used to track user sessions, store user preferences, and provide a personalized experience. Flask, a popular web framework for Python, provides built-in support for working with cookies. In this article, we will explore Flask cookies and how to implement them in your Flask applications.

What are Cookies?

Cookies are text files that contain small amounts of data, usually in the form of key-value pairs, which are stored on a user’s device by a website. When a user visits a website, the web server sends cookies to the user’s browser, which then stores the cookies locally. The next time the user visits the same website, the browser sends the cookies back to the server, allowing the website to recognize the user and provide a personalized experience.

Uses of Cookies

Cookies are commonly used for various purposes in web development, such as:

1. Session management: Cookies can be used to track user sessions and maintain state information across multiple requests from the same user.

2. User authentication: Cookies can store information about a user’s login status, allowing websites to remember logged-in users and provide personalized content.

3. Personalization: Cookies can store user preferences and settings, allowing websites to provide a customized experience for each user.

4. Analytics: Cookies can be used to track user behavior and gather usage statistics for website analysis.

Flask and Cookies

Flask is a popular micro web framework for Python that provides a simple and lightweight way to build web applications. It also includes built-in support for handling cookies, making it easy to implement cookie functionality in your Flask applications.

Flask uses the request and response objects to work with cookies. The request object allows you to access the cookies sent by the user’s browser, while the response object allows you to set cookies to be sent back to the browser.

Setting Cookies in Flask

To set a cookie in Flask, you can use the response object’s set_cookie method. The set_cookie method takes several parameters, including the cookie name, value, and optional parameters such as expiration time, domain, and path. Here’s an example:

from flask import Flask, Response

app = Flask(__name__)

@app.route('/')
def pythongeeks_set_cookie():
   resp = Response('Cookie has been set!')
   resp.set_cookie('username', 'john', max_age=3600)  # set cookie with name 'username' and value 'john' with an expiration time of 1 hour
   return resp


if __name__ == '__main__':
   app.run(debug=True)

In this example, the set_cookie method is called on the resp object to set a cookie with the name ‘username’ and the value ‘john’. The max_age parameter is used to set the expiration time of the cookie to 1 hour (3600 seconds).

Getting Cookies in Flask

To retrieve cookies in Flask, you can use the request object’s cookies attribute, which is a dictionary-like object that contains the cookies sent by the user’s browser. Here’s an example:

from flask import Flask, request


app = Flask(__name__)


@app.route('/')
def pythongeeks_get_cookie():
   username = request.cookies.get('username')  # retrieve the value of the 'username' cookie
   return f'Hello {username}!' if username else 'No username cookie found.'


if __name__ == '__main__':
   app.run(debug=True)

In this example, the request.cookies.get() method is called to retrieve the value of the ‘username’ cookie from the `request` object. The retrieved value is then used to display a personalized greeting using the retrieved username, or a generic message if the cookie is not found.

Updating and Deleting Cookies in Flask

In addition to setting and retrieving cookies, Flask also provides methods for updating and deleting cookies. You can use the response object’s set_cookie method again to update a cookie by simply setting a new value for the desired cookie name. Here’s an example:

from flask import Flask, Response, request

app = Flask(__name__)

@app.route('/')
def pythongeeks_update_cookie():
   username = request.cookies.get('username')  # retrieve the current value of the 'username' cookie
   if username:
       # update the 'username' cookie with a new value
       resp = Response(f'Hello {username}! The cookie has been updated.')
       resp.set_cookie('username', 'jane', max_age=3600)
       return resp
   else:
       return 'No username cookie found.'


if __name__ == '__main__':
   app.run(debug=True)

In this example, the set_cookie method is called again on the resp object to update the value of the ‘username’ cookie from ‘john’ to ‘jane’.

To delete a cookie, you can use the response object’s delete_cookie method, which takes the name of the cookie as a parameter. Here’s an example:

from flask import Flask, Response, request


app = Flask(__name__)


@app.route('/')
def pythongeeks_delete_cookie():
   username = request.cookies.get('username')  # retrieve the current value of the 'username' cookie
   if username:
       # delete the 'username' cookie
       resp = Response(f'Goodbye {username}! The cookie has been deleted.')
       resp.delete_cookie('username')
       return resp
   else:
       return 'No username cookie found.'


if __name__ == '__main__':
   app.run(debug=True)

In this example, the delete_cookie method is called on the resp object to delete the ‘username’ cookie.

Best Practices for Using Cookies in Flask

When working with cookies in Flask or any other web framework, it’s important to follow best practices to ensure security and protect user privacy. Here are some best practices to keep in mind:

1. Use secure cookies:

Cookies can be marked as secure, which means they will only be sent over HTTPS connections. You can use the secure parameter in the set_cookie method to mark a cookie as secure.

For example

resp.set_cookie(‘username’, ‘john’, secure=True). This helps protect sensitive information from being intercepted by attackers.

2. Set appropriate expiration times:

Set reasonable expiration times for your cookies to control how long the data stored in cookies will be available to the browser. Avoid setting long expiration times, as this can result in stale data being stored on the user’s device.

3. Don’t store sensitive information in cookies:

Avoid storing sensitive information such as passwords, credit card numbers, or other personally identifiable information (PII) in cookies. Instead, use server-side session management techniques to store sensitive data securely.

4. Validate and sanitize cookie data:

Always validate and sanitize any data that is stored in cookies to prevent attacks such as cross-site scripting (XSS) or SQL injection. Never trust data that is sent by the user’s browser and always validate and sanitize it before using it in your application.

5. Provide clear cookie policy:

Inform users about the use of cookies on your website and provide them with an option to opt-out if possible. Follow applicable laws and regulations related to cookies, such as the General Data Protection Regulation (GDPR) in the European Union.

Conclusion

In conclusion, cookies are a valuable tool in web development, allowing for the storage of small amounts of data on the user’s browser. Flask, a popular web framework in Python, provides built-in functionality for handling cookies with its request and response objects. With Flask cookies, you can easily set, retrieve, update, and delete cookies to personalize user experiences and enhance the functionality of your web applications.

However, it’s important to follow best practices when working with cookies to ensure security and protect user privacy.  By using Flask cookies responsibly and following best practices, you can enhance the user experience of your web applications and provide personalized and dynamic content to your users while maintaining their privacy and security. Happy coding with Flask cookies!

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


PythonGeeks Team

PythonGeeks Team is dedicated to creating beginner-friendly and advanced tutorials on Python programming, AI, ML, Data Science and more. From web development to machine learning, we help learners build strong foundations and excel in their Python journey.

Leave a Reply

Your email address will not be published. Required fields are marked *