Flask cookies


Cookies in Flask web applications. We will tackle flask cookies in this tutorial and also make use of them in the flask web application.

What are cookies?

Cookies can also be referred to as HTTP Cookies. They are text files stacked away on a user device. Every cookie can be stacked away for a particular expiry time depending on the browsers cookie setting used by the user or can be stored permanently. When the cookie gets to the expiry date, it gets removed automatically from the user browser. Cookies remaining on the users' patch, monitors, and remember the activity of the user on the web. The info is used for future references for the user's site experience.

Related course: Create Web Apps with Python Flask

How do cookies work?

HTTP protocol doesn't have a state, this implies that servers can't differentiate whether a user is visiting a particular site for the first time or otherwise. In a bid to find a solution to this situation, the site make use of cookies. Hence when a user visits a site for the first time, there will be no cookie generated for the user by the site. The server generates a fresh cookie and sends it to the user's device by itself.

On subsequent visits, the users' device will bind the cookie to the request and send it. The server recovers the cookies from the sent request object and makes use of the info from the cookie to better the site's user experience.

Why use Cookies?

In simple words, cookies are used to offer a better experience for the user on the site by stacking away and tracking the activity of the user. In addition, they save information like site domain, expiry date, and path also.

Few places where cookies play a good part include:

  • Social media web pages like Instagram and Twitter where you close the page without logging out, and the next time you try to log in or visit the site your account is still logged in.
  • eCommerce webpages where you get recommendations on a specific product as a result of your previously searched info.
  • Forums with login functionality

You get to do all of these with the help of cookies.

Active participation with arranging Flask Cookies

Cookies are fixed on the response object in the flask. Meaning that the server sends cookies to the user tagged with a response. This is done by using make_response() function.

Once the response is fix, you use the set_cookie() function to tag the cookie to it. The cookie take these properties: response.set_cookie('Title','Value','Expiry Time')

Hence the code resembles this:

@app.route('/setcookie')
def setcookie():
    resp = make_response(f"The Cookie has been set")
    resp.set_cookie('Name','AskPython')
    return resp

Quite easy right! Next is to retrieve the cookie back from the user. The cookie is returned along with the request to the server. You recover it by using the request.cookies.get()function. Thus you should consider this code:

@app.route('/getcookie')
def getcookie():
    name = request.cookies.get('Name', None)
    return f"The Site : {name}"

In this patch cookie info is stacked away in the name variable.

Thus the ending main application fill will be:

from flask import Flask, make_response, request
 
app = Flask(__name__)
 
@app.route('/setcookie')
def setcookie():
    resp = make_response(f"The Cookie has been Set")
    resp.set_cookie('Name','AskPython')
    return resp
 
@app.route('/getcookie')
def getcookie():
    name = request.cookies.get('Name')
    return f"The Site : {name}"
 
app.run(host='localhost', port=5000)

Implementing these codes

/setcookie Launch the server and go to “/setcookie“

/getcookie And to “/getcookie“

Awesome! Final remarks:

Done!

That’s it about Flask cookies. To understand better, try out these codes on your own.

Enjoy coding!! Catch you some other time.