Introduction

Cookies are small pieces of data that a web server sends to a user's web browser for storage. They are often used for maintaining user sessions, storing preferences, and tracking user behavior. In this guide, we'll explore how to work with cookies in Flask, including setting, getting, and deleting cookies in your web applications.


Step 1: Setting Cookies

Flask allows you to set cookies in the response using the `set_cookie` method. Here's an example of setting a cookie:

from flask import Flask, make_response
app = Flask(__name)
@app.route('/set_cookie')
def set_cookie():
resp = make_response('Cookie is set!')
resp.set_cookie('user', 'JohnDoe')
return resp

Step 2: Getting Cookies

To retrieve cookies in your Flask application, you can use the `request.cookies` dictionary. Here's how you can get the value of a cookie:

from flask import Flask, request
app = Flask(__name)
@app.route('/get_cookie')
def get_cookie():
user = request.cookies.get('user')
return f'User: {user}'

Step 3: Deleting Cookies

You can delete a cookie by setting its expiration date to the past. This will effectively remove the cookie from the user's browser. Here's an example of deleting a cookie:

from flask import Flask, make_response
app = Flask(__name)
@app.route('/delete_cookie')
def delete_cookie():
resp = make_response('Cookie is deleted!')
resp.set_cookie('user', '', expires=0)
return resp

Step 4: Cookie Options

Flask allows you to set various options when working with cookies, such as the expiration date, domain, and secure flags. Here's an example of setting a cookie with custom options:

from flask import Flask, make_response
app = Flask(__name)
@app.route('/custom_cookie')
def custom_cookie():
resp = make_response('Custom Cookie is set!')
resp.set_cookie('custom', 'value', max_age=3600, domain='.example.com', secure=True)
return resp

Conclusion

Working with cookies in Flask is essential for web application development. Cookies are versatile and allow you to store user-specific data and maintain user sessions. By following the steps in this guide, you can effectively use cookies to enhance the functionality of your Flask applications.