0
0
Flaskframework~5 mins

How cookies work in HTTP in Flask

Choose your learning style9 modes available
Introduction

Cookies help websites remember you by storing small pieces of information on your browser. This makes your experience smoother and personalized.

Remembering a user login so they don't have to sign in every time.
Keeping track of items in a shopping cart on an online store.
Saving user preferences like language or theme.
Tracking user visits to show customized content.
Managing sessions securely between the browser and server.
Syntax
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.

Examples
This sets a cookie named theme with the value dark in the user's browser.
Flask
resp.set_cookie('theme', 'dark')
This reads the username cookie sent by the browser, if it exists.
Flask
username = request.cookies.get('username')
This deletes the username cookie from the browser.
Flask
resp.delete_cookie('username')
Sample Program

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.

Flask
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)
OutputSuccess
Important Notes

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.

Summary

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.