Flask by Example: Cookie Data Structure
Cookies are small pieces of data stored on the client's browser. Unlike sessions, raw cookies are not signed and can be modified by the user, so they should not be used for sensitive data.
Code
from flask import Flask, make_response, request
app = Flask(__name__)
@app.route('/')
def index():
# Read a cookie
username = request.cookies.get('username')
if username:
return f'Welcome back, {username}!'
return 'Hello, Stranger!'
@app.route('/set_cookie')
def set_cookie():
resp = make_response('Cookie has been set!')
# Set a cookie
resp.set_cookie('username', 'flask_user', max_age=60*60*24)
return resp
@app.route('/delete_cookie')
def delete_cookie():
resp = make_response('Cookie has been deleted!')
# Delete a cookie (by setting it to expire immediately)
resp.set_cookie('username', '', expires=0)
return respExplanation
Cookies are small key-value pairs stored by the browser. In Flask, you can read them from the request.cookies dictionary and set them using the response.set_cookie() method.
Since the request object is read-only, you often need to use make_response() to create a response object first. This allows you to attach the cookie headers before sending the response back to the client.
Warning: Never trust data from cookies for security purposes unless it is signed (like Flask Sessions). Users can easily modify the cookies stored in their browser, so they should not be used for sensitive data or authorization checks.
Code Breakdown
request.cookies.get('username') reads the cookie. Using .get() avoids an error if the cookie doesn't exist.resp.set_cookie() adds the Set-Cookie header. max_age sets how long the cookie persists in seconds (here, 24 hours).expires=0).
