Cookies (Flask)
A cookie is a small piece of data the server asks the browser to store and send back on later requests. In Flask you read cookies from request.cookies and set them with response.set_cookie().
Flask
Cookies let a stateless web app remember small bits of information between requests, like a theme preference or a tracking id. Reading is simple: request.cookies.get('theme'). Setting requires a Response object so you can call set_cookie() on it before returning.
Important options on set_cookie include max_age (lifetime in seconds), httponly=True (hides the cookie from JavaScript, mitigating XSS theft), secure=True (only sent over HTTPS), and samesite to limit cross-site sending.
Flask's session is itself implemented as a special signed cookie, so prefer session for anything that must not be tampered with rather than rolling your own cookie.
Syntax
request.cookies.get("name")
resp.set_cookie("name", "value", max_age=3600)Examples
Python
from flask import request, make_response
@app.route("/theme/<name>")
def set_theme(name):
resp = make_response(f"Theme set to {name}")
resp.set_cookie("theme", name, max_age=86400, httponly=True)
return resp