A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/flask-cookies/ below:

Flask Cookies - GeeksforGeeks

Flask Cookies

Last Updated : 23 Jul, 2025

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: 

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 Login Application in Flask using cookies

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

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:

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).

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4