Cookies
Cookies are small pieces of data that are sent from the server and stored in the user's web browser. Cookies are used to remember user preferences, keep users logged in, and track user activity. Flask provides a simple way to set and retrieve cookies.
Syntax
response.set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)
- key: the name of the cookie
- value: the value to set for the cookie
- max_age: the maximum age of the cookie in seconds
- expires: the date and time that the cookie expires
- path: the URL path that the cookie is valid for
- domain: the domain that the cookie is valid for
- secure: if True, the cookie can only be sent over HTTPS connections
- httponly: if True, the cookie is inaccessible from JavaScript
- samesite: specifies the SameSite attribute for the cookie. Possible values are 'Strict', 'Lax', or None.
request.cookies.get(key, default=None)
- key: the name of the cookie to retrieve
- default: the value to return if the cookie is not found
Example
from flask import Flask, make_response, request
app = Flask(__name__)
@app.route('/')
def index():
response = make_response('Hello, World!')
response.set_cookie('username', 'bob')
return response
@app.route('/user')
def user():
username = request.cookies.get('username', default='Guest')
return f'Hello, {username}!'
Output
Visiting http://localhost:5000/
will set the 'username' cookie to 'bob'. Visiting http://localhost:5000/user
will display the message "Hello, bob!".
Explanation
In the above example, the set_cookie()
function is used to set the 'username' cookie to 'bob' when the user visits the main route ('/'). The request.cookies.get()
function is used to retrieve the 'username' cookie value when the user visits the '/user' route. If the 'username' cookie is not found, the value 'Guest' will be used as a default.
Use
Cookies can be used to store user preferences, keep users logged in, and track user activity. They can also be used for session management to identify returning users and provide personalized experiences.
Important Points
- Cookies can be accessed and modified by the user, so they should not be used to store sensitive data.
- Cookies have a limited size, so they should be used sparingly.
- The SameSite attribute should be set to 'Strict' or 'Lax' to prevent cross-site request forgery attacks.
Summary
Cookies are a simple mechanism for storing small amounts of data on the user's browser. They are commonly used for session management, user preferences, and tracking user activity. Flask provides a simple way to set and retrieve cookies using the set_cookie()
and request.cookies.get()
functions.