Open In App

Flask Cookies

Last Updated : 24 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Cookies store user data in the browser as key-value pairs, allowing websites to remember logins, preferences, and other details. This helps improve the user experience by making the site more convenient and personalized.

Make sure that flask is already installed on our system - Flask Installation

Setting Cookies in Flask

set_cookie( ) method: Using this method we can generate cookies in any application code. The syntax for this cookies setting method:

Response.set_cookie(key, value = '', max_age = None, expires = None, path = '/', domain = None, secure = None, httponly = False)

Parameters: 

  • key – Name of the cookie to be set.
  • value – Value of the cookie to be set.
  • max_age – should be a few seconds, None (default) if the cookie should last as long as the client’s browser session.
  • expires – should be a datetime object or UNIX timestamp.
  • domain – To set a cross-domain cookie.
  • path – limits the cookie to given path, (default) it will span the whole domain.

Example:

Python
from flask import Flask, request, make_response

app = Flask(__name__)

# Using set_cookie( ) method to set the key-value pairs below.
@app.route('/setcookie')
def setcookie():
  
      # Initializing response object
    resp = make_response('Setting the cookie') 
    resp.set_cookie('GFG','ComputerScience Portal')
    return resp

app.run()

Running the code in Visual Studio Code application.

My Visual Studio Code terminal

Output: Go to the above-mentioned url in the terminal -For Example - http://127.0.0.1:5000/route-name.  Here the route-name is setcookie.

Output

Getting Cookies in Flask

cookies.get( )

This get( ) method retrieves the cookie value stored from the user's web browser through the request object.

Python
from flask import Flask, request, make_response
app = Flask(__name__)

# getting cookie from the previous set_cookie code
@app.route('/getcookie')
def getcookie():
    GFG = request.cookies.get('GFG')
    return 'GFG is a '+ GFG

app.run()

Output:

getcookie
getcookie

Login Application in Flask using cookies

Let's create a simple login page in Flask using cookies.

  • First, create the main Python file, app.py.
  • Then, design the login page Login.html, where users can enter their username and password.
  • In app.py, store the username as a cookie to track the logged-in user.
  • Retrieve the stored cookie from the browser and display it on the user details page.

app.py

Python
from flask import Flask, request, make_response, render_template

app = Flask(__name__)

@app.route('/', methods = ['GET'])
def Login():
   return render_template('Login.html')

@app.route('/details', methods = ['GET','POST'])
def login():
    if request.method == 'POST':
        name = request.form['username']
        output = 'Hi, Welcome '+name+ ''
        resp = make_response(output)
        resp.set_cookie('username', name)
    return resp

app.run(debug=True)

Login.html

HTML
<!DOCTYPE html>
<html>
    <head>
        <title>Login</title>
    </head>
    <body>
        <form method="post" action="/details">
            <label for="username">Username</label>
            <input type="text" name="username" id="username"/> 
            <br/>
            <br>
            <label for="password">Password</label>
            <input type="password" name="password" id="password"/> 
            <br/>
            <br>
            <input type="submit" name="submit" id="submit" value="Login"/> 
        </form>
    </body>
</html>

Output:

Login Page
User Logging
User Logged In and Cookie Tracker

From the image above, we can see the website's cookies. The 'username' is the key, and its value 'Greeshma' shows that cookies store data as key-value pairs.

To view cookies in your browser:

  • Click the three-dot menu in the top-right corner.
  • Go to More Tools > Developer Tools.
  • Open the Application tab.  

Tracking Website Visitors Using Cookies

We will track the number of visitors to our website using cookies. Since we haven't previously stored a "visitors count" variable, the cookie will default to 0 (as per Python's dictionary behavior).

  • For a first-time visitor, the count starts at 0.
  • With each visit, the count increases.
  • The make_response() function is used to generate a response object and set the updated visitor count in the cookie.
Python
from flask import Flask, request, make_response

app = Flask(__name__)
app.config['DEBUG'] = True


@app.route('/')
def vistors_count():
    # Converting str to int
    count = int(request.cookies.get('visitors count', 0))
    # Getting the key-visitors count value as 0
    count = count+1
    output = 'You visited this page for '+str(count) + ' times'
    resp = make_response(output)
    resp.set_cookie('visitors count', str(count))
    return resp


@app.route('/get')
def get_vistors_count():
    count = request.cookies.get('visitors count')
    return count


app.run()

Output: Url - http://127.0.0.1:5000

Output

Url for below output- http://127.0.0.1:5000/get

Visitors count output using cookies

In the above output screenshot, the value of the website visitors count is retrieved using request.cookies.get( ) method.

Cookies Tracking in Browser

Cookie Tracker for visitors count application

The flask cookies can be secured by putting the secure parameter in response.set_cookie('key', 'value', secure = True) and it is the best-recommended practice to secure cookies on the internet.


Next Article

Similar Reads