The Wayback Machine - https://web.archive.org/web/20241001005146/https://www.geeksforgeeks.org/flask-cookies/
Open In App

Flask Cookies

Last Updated : 05 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Flask is a lightweight, web development framework built using python language. Generally, for building websites we use HTML, CSS and JavaScript but in flask the python scripting language is used for developing the web-applications.

To know more about Flask and how to run an application in Flask: Flask – First Application Creation

What are Cookies?

Technically, cookies track user activity to save user information in the browser as key-value pairs, which can then be accessed whenever necessary by the developers to make a website easier to use. These enhances the personal user experience on a particular website by remembering your logins, your preferences and much more. 

For running a flask application, we need to have some prerequisites like installing the flask. 

Prerequisites:

Use the upgraded version of pip by below command in your terminal. In this article, I am using Visual Studio Code to run my flask applications.

Python -m pip install –upgrade pip
Python -m pip install flask 

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:

Python3




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.

Python3




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:

 

Login Application in Flask using cookies

Let’s develop a simple login page with Flask using cookies. First, we are creating the main python file – app.py in our code editor. Next, we will create the UI of our web page which is Login.html where the user can enter his username and password. In this app.py, we are storing the username as cookie to know which user logged in to the website. In the below code, we are requesting the stored cookie from the browser and displaying it on the next page which routes to user details page.

app.py

Python3




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 above image, the user can also see the cookies of a website. Here, ‘username’ is the key and its value is ‘Greeshma’ which reminds us that cookies are generally key-value pairs. To see the cookies in your browser, click the last 3 dots on the browser’s right corner>> More Tools>>Developer Tools>>Application window.   

Getting website Visitors counted through cookies

In the below code, we want to know the number of visitors visiting our website. We are first retrieving the visitor’s count by the usage of cookies. But there is no variable named visitors count that we created previously. As this key(visitors count) is not present in the dictionary, it will take the value of 0 that is specified in the second parameter as per the dictionary collection in python. Hence, for the first-time visitors count=0, then incrementing the count according to the user’s visit to the website. The make_response( ) gets the response object and is used for setting the cookie. 

Python3




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.



Previous Article
Next Article

Similar Reads

Documenting Flask Endpoint using Flask-Autodoc
Documentation of endpoints is an essential task in web development and being able to apply it in different frameworks is always a utility. This article discusses how endpoints in Flask can be decorated to generate good documentation of them using the Flask-Autodoc module. This module provides the following features - Helps to document endpoints of
4 min read
How to use Flask-Session in Python Flask ?
Flask Session - Flask-Session is an extension for Flask that supports Server-side Session to your application.The Session is the time between the client logs in to the server and logs out of the server.The data that is required to be saved in the Session is stored in a temporary directory on the server.The data in the Session is stored on the top o
4 min read
How to Integrate Flask-Admin and Flask-Login
In order to merge the admin and login pages, we can utilize a short form or any other login method that only requires the username and password. This is known as integrating the admin page and Flask login since it simply redirects users to the admin page when they log in. Let's is how to implement this in this article. Integrate Flask Admin and Fla
8 min read
Minify HTML in Flask using Flask-Minify
Flask offers HTML rendering as output, it is usually desired that the output HTML should be concise and it serves the purpose as well. In this article, we would display minification of output routes of Flask responses using the library - Flask-Minify. Advantages of MinificationWebsites load faster as fewer lines are there to upload and download.Ban
12 min read
Flask URL Helper Function - Flask url_for()
In this article, we are going to learn about the flask url_for() function of the flask URL helper in Python. Flask is a straightforward, speedy, scalable library, used for building, compact web applications. It is a micro framework, that presents developers, useful tools, and, features, for coding REST APIs, and backend data processing, of web apps
11 min read
response.cookies - Python requests
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.cookies out of a
2 min read
Retrieving Cookies in Python
Retrieving cookies in Python can be done by the use of the Requests library. Requests library is one of the integral part of Python for making HTTP requests to a specified URL. The below codes show different approaches to do show: 1. By requesting a session: # import the requests library import requests # initialize a session session = requests.Ses
1 min read
Adding and Deleting Cookies in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What
3 min read
Managing Cookies for User Tracking and Personalization in Python
The prevalence of cookies has grown markedly in recent years. Also known as computer cookies, HTTP cookies, web cookies, or internet cookies, they are instrumental in enhancing our online experiences. Created to identify users during website visits, cookies enable sites to track and recognize user devices subsequently. By streamlining web experienc
6 min read
Python Falcon - Cookies
In the world of web development, managing user sessions is a fundamental aspect, and cookies serve as a crucial tool in achieving this. Python Falcon, a lightweight and efficient web framework, allows developers to seamlessly handle cookies within their applications. In this article, we will learn about cookies in Python Falcon. What are Falcon-Coo
5 min read
How to save and load cookies in Selenium using Python
In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Python. In this article, we will learn all the steps t
4 min read
Python Flask - ImmutableMultiDict
MultiDict is a sub-class of Dictionary that can contain multiple values for the same key, unlike normal Dictionaries. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list. Example: C/C++ Code from werkzeug.datastructures import MultiDict orders = MultiDict([(1, 'GFG'
2 min read
Handling 404 Error in Flask
Prerequisite: Creating simple application in Flask A 404 Error is showed whenever a page is not found. Maybe the owner changed its URL and forgot to change the link or maybe they deleted the page itself. Every site needs a Custom Error page to avoid the user to see the default Ugly Error page. GeeksforGeeks also has a customized error page. If we t
4 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
How to Build a Simple Android App with Flask Backend?
Flask is an API of Python that allows us to build up web applications. It was developed by Armin Ronacher. Flask’s framework is more explicit than Django’s framework and is also easier to learn because it has less base code to implement a simple web-Application. A Web-Application Framework or Web Framework is the collection of modules and libraries
8 min read
Subdomain in Flask | Python
Prerequisite: Introduction to Flask In this article, we will learn how to setup subdomains in Flask. But first, let's go through the basic like what is DNS and subdomains. Domain Name System (DNS): The Domain Name System (DNS) is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or
3 min read
Setup API for GeeksforGeeks user data using WebScraping and Flask
Prerequisite: WebScraping in Python, Introduction to Flask In this post, we will discuss how to get information about a GeeksforGeeks user using web scraping and serve the information as an API using Python's micro-framework, Flask. Step #1: Visit the auth profile To scrape a website, the first step is to visit the website. Step #2: Inspect the Pag
3 min read
Python | Build a REST API using Flask
Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Flask framework. Flask is a popular micro framework f
3 min read
Create a Weather app using Flask | Python
Prerequisite : Flask installation Flask is a lightweight framework written in Python. It is lightweight because it does not require particular tools or libraries and allow rapid web development. today we will create a weather app using flask as a web framework. this weather web app will provide current weather updates of cities searched. Basic setu
2 min read
Todo list app using Flask | Python
There are many frameworks that allow building your webpage using Python, like Django, flask, etc. Flask is a web application framework written in Python. Flask is based on WSGI(Web Server Gateway Interface) toolkit and Jinja2 template engine. Its modules and libraries that help the developer to write applications without writing the low-level codes
3 min read
Deploy Machine Learning Model using Flask
Machine learning is a process that is widely used for prediction. N number of algorithms are available in various libraries which can be used for prediction. In this article, we are going to build a prediction model on historical data using different machine learning algorithms and classifiers, plot the results, and calculate the accuracy of the mo
11 min read
Dockerize your Flask App
Python provides many ways to distribute your python projects. One such way is by using an important technology called Docker. Docker is an open-source application that allows administrators to create, manage, deploy, and replicate applications using containers. It is basically a platform that enables developers to make their applications portable b
4 min read
Sending Emails Using API in Flask-Mail
Python, being a powerful language don’t need any external library to import and offers a native library to send emails- “SMTP lib”. “smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send emails to any valid email id on the internet. This article revolves around how we can send bulk customised emails to a group
3 min read
Deploying a TensorFlow 2.1 CNN model on the web with Flask
When starting to learn Machine Learning, one of the biggest issues people face is deploying whatever they make to the web for easier demonstration/use. This article will help those beginners bridge the gap between creating a TensorFlow model and deploying it on the web with Flask and hopefully gain some insight on the issues TensorFlow and Flask ha
4 min read
Using JWT for user authentication in Flask
Pre-requisite: Basic knowledge about JSON Web Token (JWT)I will be assuming you have the basic knowledge of JWT and how JWT works. If not, then I suggest reading the linked Geeksforgeeks article. Let's jump right into the setup. Ofcourse, you need python3 installed on your system. Now, follow along with me. I will be using a virtual environment whe
7 min read
Retrieving HTML Form data using Flask
Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web application frameworks. Read this article to know more about Flask Create form as
3 min read
Setting up Google Cloud SQL with Flask
Setting up a database can be very tricky, yet some pretty simple and scalable solutions are available and one such solution is Google Cloud SQL. Cloud SQL is a fully-managed database service that makes it easy to set up, maintain, and administer your relational PostgreSQL and MySQL databases in the cloud. Setting it up can be both tricky and simple
6 min read
Login and Registration Project Using Flask and MySQL
Project Title: Login and registration Project using Flask framework and MySQL Workbench. Type of Application (Category): Web application. Introduction: A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, inclu
6 min read
Profile Application using Python Flask and MySQL
A framework is a code library that makes a developer's life easier when building web applications by providing reusable code for common operations. There are a number of frameworks for Python, including Flask, Tornado, Pyramid, and Django. Flask is a lightweight web application framework. It is classified as a micro-framework because it does not re
10 min read
How to Connect Mongodb Compass to Flask
An effective GUI tool for managing and visualizing MongoDB data is MongoDB Compass. On the other hand, a well-liked Python web framework for creating web apps is called Flask. Integrating your MongoDB data into your Flask web application may benefit from connecting MongoDB Compass to Flask. Through your Flask web application, you can quickly read,
2 min read