Using cookies in Flask

We’ll look at Flask cookies and use them in the Flask web application in this tutorial. So strap in, and let’s get this party started.

What exactly are cookies?

Cookies, or more precisely, HTTP cookies, are text files saved on the client machine. Based on the cookie settings in the client browser, each cookie might be stored permanently or for a defined expiry time.

The cookie is automatically erased from the client browser when it reaches its expiration date and time. Client-side cookies keep track of and remember the user’s online activities. This data is then used to improve the user’s overall experience on the site.

How do they work?

HTTP refers to a stateless protocol, which means the server has no way of knowing if a user is visiting the site for the first time or not. Sites utilize cookies to solve this problem.

As a result, when a client sees a site for the first time, the site does not set any cookies on the client. Consequently, the server produces a new cookie and transmits it to the client.

As a result, the client machine will attach the cookie to the request and send it on subsequent visits. The server then obtains the cookies from the request object and utilizes them to improve the user experience on the site.

What is the purpose of cookies?

In a nutshell, cookies improve the user’s experience on the site by storing and tracking the user’s activities. They also save information like the site’s expiration date, route, and domain.

Cookies are used in a variety of settings, including:

  • You may have observed that when you leave an eCommerce or social networking website like Facebook without signing out, your account remains signed in the next time you return.
  • You can get product recommendations based on your browser’s previous search history on many eCommerce websites. All of this is accomplished through the use of cookies.

Cookies in Flask

A cookie is a text file saved on a client’s computer. Its goal is to recall and track information about a client’s usage to improve the visitor experience and site statistics.

A cookie’s attribute is contained in a Request object. It’s a dictionary object that contains all of the cookie variables and their values that a client has sent. A cookie also saves the site’s expiry time, path, and domain name, among other things.

Cookies are stored on the client’s machine by the server. They are associated with the client’s request to that server in all subsequent transactions until the cookie’s lifetime expires, or the server’s specific web page erases it.

The cookies are associated with the Request object in the Flask as a dictionary object that contains all of the cookie variables and their values sent by the client. Flask makes setting the website’s expiry time, path, and domain name easy.

Create cookie

Cookies are set on the response object in Flask. To get a response object from a view function’s return value, use the make_response() function. Then, to store a cookie, utilize the response object’s set_cookie() function.

It’s simple to read a cookie backward. The request.cookies method get() helps to read a cookie. A simple form appears when you access the ‘/’ URL in the following Flask application.

@app.route('/')
def index():
  return render_template('index.html')

The HTML page below has a single text input.

<html>
   <body>
      <form action = "/code/set/cookie" method = "POST">
         <p><h3>Please Enter userID</h3></p>
         <p><input type = 'text' name = 'code'/></p>
         <p><input type = 'submit' value = 'Login'/></p>
      </form>
   </body>
</html>

Setting the cookie

The set_cookie() method in Flask is used to set cookies on the response object. The view function’s make_response() process creates the response object.

response.setCookie(<title>, <content>, <expiry time>)

The form submission is directed to the URL ‘/code/set/cookie’. The linked view function creates a userID cookie and renders a new page.

@app.route('/code/set/cookie', methods = ['POST', 'GET'])
def setcookie():
   if request.method == 'POST':
   user = request.form['code']
   
   resp = make_response(render_template('readcookie.html'))
   resp.set_cookie('userID', user)
   
   return resp

The cookie has been set if you open the developer tools in your browser, go to the storage tab, and pick cookies from the menu on the left.

Flask cookies are enabled in the developer tools.

Parameters in cookie

You’ll see that cookies contain various options in the developer tools, including key, value, domain, path, and more, which may be configured using Flask. The parameters listed below are passed to the set_cookie function:

set_cookie(
    key,
    value='',
    max_age=None,
    expires=None,
    path='/',
    domain=None,
    secure=False,
    httponly=False,
    samesite=None
)
ParameterDefault valueDescription
keyrequiredThe key’s name of the cookie
value“”The cookie’s value
max_ageNoneBy default, it is None, but it is the count of seconds
expiresNoneThe cookie expiry date, – a datetime object
pathNoneRestricts the cookie to a specific path
domainNoneset a domain that can read the cookie (default is the initial domain setter)
secureFalseIf True, the cookie is strictly available over HTTPS
httponlyFalseDisallow JavaScript to access the cookie (Limited browser support)
samesiteFalseLimits the scope of where the cookie is accessible to the same site

These features provide us with a lot of control over how our cookies work and many options for managing them. Set the max_age and path keys to 30 seconds, respectively, and the /cookies path to:

resp.set_cookie(
    "code",
    value="underscored",
    max_age=10,
    path=request.path
)

To get the current route’s path, we used the request. path. Examining your browser’s developer’s tools console, you’ll notice that our cookie now has an expiry date and a value for path of /cookies. We’ll return to max_age in a moment with another example, but first, let’s go over how to access cookies.

Reading the cookies

Alternatively, use the get() function of the cookies attribute associated with the Request object to read the cookies stored on the client’s system. The file ‘readcookie.html’ contains a link to another view function, getcookie(), which reads the cookie value and shows it in the browser.

request.cookies.get(<title>)
@app.route('/getcookie')
def getcookie():
   user_name = request.cookies.get('userID')
   return '<h1>welcome '+user_name+'</h1>'

The result of setting a cookie & the output of the read-back cookie is in the following complete implementation:

from flask import *  

app = Flask(__name__)  

@app.route('/cookie')  
def cookie():  
  res = make_response("<h1>cookie is set in codeunderscored</h1>")  
  res.set_cookie('code','underscored')  
  return res  

if __name__ == '__main__':  
  app.run(debug = True)  

For the website localhost:5000, you can use the preceding python script to set the cookie with the name ‘code,’ and the content ‘underscored’ on the browser.

Use the command python script.py to run this python script and view the results in your browser.

set cookie
set cookie

The cookie details can be tracked in the browser’s content settings, as seen in the figure below.

How to track cookies
How to track cookies

maximum age

Even after changing max_age in our cookie, you may find that it still appears in the developer tools. Remove the first cookie we set by commenting it out:

@app.route("/cookies")
def cookies():

    resp = make_response("Set cookies")

    cookies = request.cookies

    print(cookies)

    # resp.set_cookie(
    #     "code",
    #     value="underscored",
    #     max_age=10,
    #     path=request.path
    # )

    resp.set_cookie("theme type", "dark")
    resp.set_cookie("light", "yes")

    return resp

Refresh the page and wait around 10 seconds. You’ll note in the terminal output that we obtain the following:

{'theme type': 'dark', 'light': 'yes'}

Even though the cookie remains in the browser, it is not sent to the server. That is because the max_age value in the cookie has been set to 10 seconds. Upon the browser’s closure, it will be removed. To erase cookies from your browser, right-click on the domain in the developer tools’ cookies tab and select delete.

Deleting cookies

Set the max_age argument to 0 and call set_cookie() with the cookie’s name and any value to erase it. Add the following code directly after the cookie () view method in the main.py file.

flask_app/main.py

#...
@app.route('/delete-cookie/')
def delete_cookie():
    res = make_response("Cookie Removed")
    res.set_cookie('code', 'underscored', max_age=0)
    return res
#…

Image before deleting the cookie

before deleting cookie
before deleting cookie

Image after deleting the cookie

after deleting cookie
after deleting cookie

Login app in Flask

In this example, we’ll develop a login application in Flask that displays a login page (login.html) to the user and prompts them to input their email and password. If the password is “code,” the application will take the user to the success page (success.html), which includes a message and a link to the user’s profile (profile.html); otherwise, the user will be directed to the error page.

The application’s behavior is managed by the controller python flask script stored as login.py. It has the view functions for all of the different instances. The user’s email address is saved in a cookie on the browser. If the user’s password is “code,” the application saves the user’s email address in the browser as a cookie, then read on the profile page to display a message to the user.

The following python and HTML scripts are included in the application. The application’s directory structure is shown below.

[image]

from flask import *  

app = Flask(__name__)  

# @app.route('/cookie')  
# def cookie():  
#   res = make_response("<h1>cookie is set in codeunderscored</h1>")  
#   res.set_cookie('code','underscored')  
#   return res  

@app.route("/cookie")
def cookies():

    resp = make_response("Set cookies")

    cookies = request.cookies

    print(cookies)

    # resp.set_cookie(
    #     "code",
    #     value="underscored",
    #     max_age=10,
    #     path=request.path
    # )

    resp.set_cookie("theme type", "dark")
    resp.set_cookie("light", "yes")

    return resp

@app.route('/delete-cookie/')
def delete_cookie():
    res = make_response("Cookie Removed")
    res.set_cookie('light', 'yes', max_age=0)
    return res

@app.route('/error')  
def error():  
    return "<p><strong>Enter correct password</strong></p>"

@app.route('/')  
def login():  
    return render_template("login.html")  

@app.route('/success',methods = ['POST'])  
def success():  
    if request.method == "POST":  
        email = request.form['email']  
        password = request.form['pass']  

    if password=="code":  
        resp = make_response(render_template('success.html'))  
        resp.set_cookie('email',email)  
        return resp  
    else:  
        return redirect(url_for('error'))  

@app.route('/viewprofile')  
def profile():  
    email = request.cookies.get('email')  
    resp = make_response(render_template('profile.html',name = email))  
    return resp  

if __name__ == '__main__':  
  app.run(debug = True)  
<!-- login.html-->

<html>  
<head>  
    <title>login</title>  
</head>  
<body>  
    <form method = "post" action = "http://localhost:5000/success">  
        <table>  
            <tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>  
            <tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>  
            <tr><td><input type = "submit" value = "Submit"></td></tr>  
        </table>  
    </form>  
</body>  
</html>  

<!-- success.html -->
<html>  
<head>  
<title>success</title>  
</head>  
<body>  
    <h2>Login successful</h2>  
    <a href="/viewprofile">View Profile</a>  
</body>  
</html>  
<!-- profile.html -->

<html>  
<head>  
    <title>profile</title>  
</head>  
<body>  
    <h3>Hi, {{name}}</h3>  
</body>  
</html>  

Execution

Use the command python login.py to run the python script, then go to localhost:5000/ in your browser, as shown in the screenshots.

login interface

Submit the form. It will display a success message as well as a link to profile.html.

login successful
Login successful

or an error message if the credentials do not match.

Error because of incorrect credentials
Error because of incorrect credentials

Select View Profile from the hyperlink shown. It will display the following message after reading the cookie set by the browser as a response.

Cookie’s drawbacks

You should be aware of the drawbacks of cookies before employing them extensively in your project.

Cookies aren’t entirely safe

Because the data stored in the cookie is visible to anybody, you should not use it to store sensitive information such as passwords, credit card numbers, or other personal information.

How to turn off cookies

The majority of browsers allow users to disable cookies. When cookies are disabled, no warnings or error messages are displayed; instead, the response header used to set the cookie is ignored. Use Javascript code to notify the user that your application requires cookies to function correctly to avoid these issues.

Each cookie has a maximum data storage capacity of 4KB. Furthermore, browsers limit the number of cookies that a website can set. This limit changes depending on the browser. Some browsers allow up to 50 cookies per website, while others only allow up to 30.

Every time you request a page from the server, cookies are transmitted. Let’s say you have 20 cookies, each of which has 4KB of data. That means each request has an additional payload of 80KB!

Client-side cookie placement

Using JavaScript to set cookies is also reasonably straightforward.

document.cookie = "key=value";

It will only set the most basic sort of cookie, with no further metadata. We can additionally give the cookie some other parameters, such as:

document.cookie = "key=value; expires=DDD, DD MMM YYYY HH:MM:SS UTC";

You can also use the following syntax to add a path:

document.cookie = "key=value; expires=DDD, DD MMM YYYY HH:MM:SS UTC; path=/path";

You can then use request.cookies to access any client-side cookies.

Conclusion

Cookies refer to text files saved on the client’s computer. For a better visitor experience and website statistics, the goal is to recall and track relevant data on consumer usage.

The cookie’s properties are stored in the Flask Request object. It’s a dictionary object that contains all cookie variables and their values and the client. Furthermore, cookies save the website’s expiration time, path, and domain name.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *