🎓 A1Learner
🔍
0 of 50 lessons completed

Flask Cookies

A cookie is a small value the browser keeps. The app sets it, and the browser sends it back.

Make the app

This line imports Flask, make_response, and request together. The routes below set and read a cookie.

from flask import Flask, make_response, request

app = Flask(__name__)

Set the cookie

The view builds a response and sets a cookie named flavour with the value mint.

@app.route("/set")
def set_cookie():
    response = make_response("Cookie set")
    response.set_cookie("flavour", "mint")
    return response

Read the cookie

The view reads flavour from the cookies the browser sent. The default shows when no cookie arrives.

@app.route("/read")
def read():
    return request.cookies.get("flavour", "no cookie")

Set, then read

The test client first asks for /set, which stores the cookie. The next ask reads it back.

client = app.test_client()
client.get("/set")
print(client.get("/read").data.decode())

Example

from flask import Flask, make_response, request

app = Flask(__name__)

@app.route("/set")
def set_cookie():
    response = make_response("Cookie set")
    response.set_cookie("flavour", "mint")
    return response

@app.route("/read")
def read():
    return request.cookies.get("flavour", "no cookie")

client = app.test_client()
client.get("/set")
print(client.get("/read").data.decode())

Key points

  • set_cookie adds a cookie to a response.
  • request.cookies reads cookies the browser sent.
  • A cookie holds a name and a value.
  • Cookies remember small choices, like a flavour.

In this example, the /set route builds a response and sets a cookie named flavour to mint. The /read route reads the cookie back. The test client asks for /set first, so the cookie is stored, and the print shows mint.

Note

A cookie travels with every request after it is set.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does a view set a cookie?