0
0
Flaskframework~5 mins

Setting and reading cookies in Flask

Choose your learning style9 modes available
Introduction

Cookies help websites remember you. You can save small bits of information on a visitor's browser and read it later.

Remembering a user's login status so they don't have to log in every time.
Saving user preferences like theme color or language choice.
Tracking items in a shopping cart before checkout.
Counting how many times a user visits a page.
Storing temporary data between page requests.
Syntax
Flask
from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/set')
def set_cookie():
    resp = make_response('Cookie is set')
    resp.set_cookie('key', 'value')
    return resp

@app.route('/get')
def get_cookie():
    value = request.cookies.get('key')
    return f'Cookie value is {value}'

Use make_response() to create a response object before setting cookies.

Read cookies from request.cookies dictionary.

Examples
Sets a cookie named username with value alice.
Flask
resp.set_cookie('username', 'alice')
Reads the value of the cookie named username. Returns None if not found.
Flask
value = request.cookies.get('username')
Sets a cookie that expires after 1 hour (3600 seconds).
Flask
resp.set_cookie('session_id', 'abc123', max_age=3600)
Sample Program

This Flask app has two routes: /set sets a cookie named favorite_color with value blue that lasts one day. /get reads and shows the cookie value if it exists.

Flask
from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/set')
def set_cookie():
    resp = make_response('Cookie has been set!')
    resp.set_cookie('favorite_color', 'blue', max_age=60*60*24)  # 1 day
    return resp

@app.route('/get')
def get_cookie():
    color = request.cookies.get('favorite_color')
    if color:
        return f'Your favorite color is {color}'
    else:
        return 'No favorite color cookie found.'
OutputSuccess
Important Notes

Cookies are stored on the user's browser and sent with every request to your site.

Be careful not to store sensitive information in cookies because users can see and change them.

Use max_age or expires to control how long cookies last.

Summary

Cookies let you save small data on a user's browser to remember things.

Use set_cookie on a response to save a cookie.

Use request.cookies.get() to read a cookie value.