Cookies help websites remember you by storing small pieces of information on your browser. This makes your experience smoother and personalized.
How cookies work in HTTP in Flask
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/') def index(): username = request.cookies.get('username') if username: return f'Hello, {username}!' else: resp = make_response('Hello, Guest!') resp.set_cookie('username', 'Alice') return resp
Use request.cookies.get('cookie_name') to read a cookie sent by the browser.
Use response.set_cookie('cookie_name', 'value') to send a cookie to the browser.
theme with the value dark in the user's browser.resp.set_cookie('theme', 'dark')
username cookie sent by the browser, if it exists.username = request.cookies.get('username')username cookie from the browser.resp.delete_cookie('username')This Flask app checks if the browser sent a cookie named username. If yes, it greets the user by name. If not, it sets the cookie with the value Alice and welcomes the new visitor.
from flask import Flask, request, make_response app = Flask(__name__) @app.route('/') def index(): username = request.cookies.get('username') if username: return f'Welcome back, {username}!' else: resp = make_response('Hello, new visitor! Setting your cookie now.') resp.set_cookie('username', 'Alice') return resp if __name__ == '__main__': app.run(debug=True)
Cookies are stored on the user's browser and sent with every request to the server for that domain.
Cookies can have expiration times, making them temporary or persistent.
Always be careful with sensitive data; do not store passwords in cookies.
Cookies store small data on the browser to remember users.
Flask uses request.cookies to read and response.set_cookie() to write cookies.
Cookies improve user experience by saving preferences and login info.