SoFunction
Updated on 2025-03-01

Use of cookies and sessions in flask framework

The article introduces cookies and sessions in the flask framework. Session is a data structure saved on the server side to track the status of users. This data can be saved in clusters, databases, and files. Cookies are a mechanism for clients to save user information, used to record some user information, and are also a way to implement sessions.

WEB -> cookie & session

Since the HTTP protocol is a stateless protocol, when the server needs to record the user's status, it needs to use a certain mechanism to identify the specific user. This mechanism is Session. Typical scenarios such as shopping carts. When you click the order button, since the HTTP protocol is stateless, you do not know which user operates it. Therefore, the server needs to create a specific session for a specific user, which is used to identify the user and track the user, so that you can know how many books there are in the shopping cart. This session is stored on the server and has a unique identifier.

How does the server identify specific customers? Cookies will appear at this time. Every time an HTTP request is requested, the client will send the corresponding cookie information to the server. In fact, most applications use cookies to implement session tracking. When the session is created for the first time, the server will tell the client in the HTTP protocol that it is necessary to record a Session ID in the cookie. In the future, every time I request to send this session ID to the server, I will know who you are.

Cookies can actually be used in some convenient scenarios. Imagine that you log in to a website one time and don’t want to enter your account again when you log in next time. What should I do? This information can be written into a cookie. When visiting the website, the script on the website page can read this information and will automatically fill in the username for you, which can be convenient for users. This is also the origin of the cookie name, which gives users a little sweetness.

session and cookies in flask

The session mechanism in flask is to encrypt the sensitive data and put it in the session, and then store the session into the cookie. The next time you request, you will directly obtain the session from the cookie sent by the browser, and then obtain the data from it for decryption.

This way, the operation saves service overhead, because all data is stored to the client.

You may be worried about the security of this approach, because all data is stored in a local browser and is easily stolen, but the security is always relative, and flask also has its own special encryption algorithm for sessions, so there is no need to pay too much attention to security issues.

Session Operation

1. You need to import the session first when using sessionom

from flask import session

2.SECRET_KEY

Remember to set SECRET_KEY to encrypt data. If your secret key is changing every time you start the server, you can no longer use the previous SECRET_KEY for decryption. We can set it to a fixed value here. As mentioned in the previous article, if the data volume is large, it will be integrated separately. However, if it is only a few small settings, you can simply set the instructions in the main file, similar to the following:

#Generate random 24-bit string['SECRET_KEY'] = (24)

Value added

Because session and cookies are both dictionaries in key-value pairs, just add them directly using the dictionary method.

session['username'] = 'user1'

Value deletion

#1. Single deletion('username')
del session['username']
#2. Clear all()

Value Getting

('username')
session['username']

6. Set the expiration time (if not set, the default browser exits automatically and ends automatically)

#Configure the session parameter PERMANENT_SESSION_LIFETIME, the data type of this value is type['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) 
 = True #Default is 31 days

Handling of cookies in Flask

1. Set cookies:

Set cookies, the default validity period is temporary cookies, and the browser is closed and invalid
The validity period can be set through max_age, the unit is seconds

resp = make_response("success") # Set the response bodyresp.set_cookie("Itcast_1", "python_1", max_age=3600)

2. Get cookies

Get the cookie, through the method, the return is a dictionary, which can obtain the corresponding value in the dictionary

cookie_1 = ("Itcast_1")

3. Delete cookies

The deletion here only makes the cookie expire, not directly delete the cookie.

Delete cookies, delete_cookie(), which contains the name of the cookie

resp = make_response("del success") # Set the response bodyresp.delete_cookie("Itcast1")

Example

from flask import Flask, make_response, request
app = Flask(__name__)
@("/set_cookie")
def set_cookie():
  resp = make_response("success")
  '''
     Set cookies, the default validity period is temporary cookies, and the browser is closed and invalid
     The validity period can be set through max_age, the unit is seconds
   '''''
  resp.set_cookie("Itcast_1", "python_1")
  resp.set_cookie("Itcast_2", "python_2")
  resp.set_cookie("Itcast_3", "python_3", max_age=3600)
  return resp
 
@("/get_cookie")
def get_cookie():
  """
     Get cookies, through the way,
     Returns a dictionary, which can be used in get
   """
  cookie_1 = ("Itcast_1") # Get the value of the cookie corresponding to the name Itcast_1  return cookie_1
 
@("/delete_cookie")
def delete_cookie():
  """
    deletecookie,passdelete_cookie()Way,
    It's insidecookieName
    这里的delete只是让cookieExpired,并不是直接deletecookie
  """
  resp = make_response("del success")
  resp.delete_cookie("Itcast1")
  return resp
 
if __name__ == '__main__':
  (debug=True)

This is the article about the use of cookies and sessions in the flask framework. For more related flask cookies and session content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!