How To Use Session And Cookie In Python Flask Framework

Session is a data structure saved on the server-side, which is used to track the status of users. This data can be saved in clusters, databases, and files. Cookie is a mechanism for clients to save user data,  and it is also a way to implement Session. This article introduces how to manage Session and Cookie in Python flask framework.

1.What is Session & Cookie.

1.1 What is Session.

Because HTTP protocol is a stateless protocol, when the web server needs to record the user’s status, it needs to use some mechanism to identify the specific user. This mechanism is the so-called Session. In a typical scenario, such as a shopping cart, when someone clicks the order button to put a book into the shopping cart, because the HTTP protocol is stateless, you don’t know which user operates it. Therefore, the server needs to create a specific session for the user to identify and track it. Only in this way can you know how many books are there in the shopping cart. This session is saved on the server-side and has a unique session ID.

1.2 What is Cookie.

How does the server identify a specific client user? This is when cookies come to the stage. Each time when a client sends an HTTP request to the web server, it will send the corresponding cookie information to the server. Most applications use cookies to implement session tracking. When creating a session for the first time, the server will tell the client that it needs to record a session ID in the cookie, and later the client will send the session ID to the server for each HTTP request, then the web server can know which client sends the request for each time.

2. How To Manage Session & Cookie In Python Flask Framework.

The session mechanism in Flask is to encrypt the sensitive data and put it into a session, then save the session into a cookie. When the client makes an HTTP request for the next time, the session data is directly obtained from the cookie sent by the web browser, and then Flask program can decrypt the original session data from it. This operation saves more server overhead because the data is stored in the client.

You may worry about the security of this method because all the data is stored in the local browser, which is easy to be stolen, but the security is always relative, and Flask also has its own special encryption algorithm for Session, so you don’t have to pay too much attention to the security.

2.1 Flask Session Management.

  1. First, we need to import the Flask session package.
    from flask import session
  2. Generate a SECRET_KEY value. The SECRET_KEY is used to encrypt and decrypt session data, and if your secret key changes every time when you start the server, you can’t use the previous SECRET_KEY to decrypt session data. We can set it to a fixed value in Flask configuration file config.py like below.
    import os
    
    import binascii
    
    # Generates a random 24 bit string 
    secret_key_value = os.urandom(24)
    
    # Create the hex-encoded string value.
    secret_key_value_hex_encoded = binascii.hexlify(out)
    
    # Set the SECRET_KEY value in Flask application configuration settings.
    app.config['SECRET_KEY'] = secret_key_value_hex_encoded
  3. Set data in Flask session. Because session and cookie are dictionaries in the form of key-value pairs, you can add them directly by dictionary method.
    session['email'] = '[email protected]'
  4. Get Flask session data value by key.
    session.get('email')
    session['email']
  5. Set Flask session expiration time ( if it is not set, the session will expire automatically when the web browser exit ).
    # Set session parameter PERMANENT_SESSION_LIFETIME's value in config.py file. The PERMANENT_SESSION_LIFETIME's value is a datetime.timedelay data type.
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
    
    session.permanent = True
  6. Remove Flask session data.
    # Remove one session data.
    session.pop('username')
    del session['username']
    
    # Remove all session data. 
    session.clear()

2.1 Flask Cookie Management.

  1. Set cookie. The default cookie is a temporary cookie, which will be invalid when the browser is closed. You can set cookie max_age value to set the cookie validation period in seconds.
    # Get the web server HTTP response.
    resp = make_response("success")
    
    # Set cookie in the HTTP response object. The cookie name is cookie_name, the cookie value is cookie_value, it will expire in 3600 seconds.
    resp.set_cookie("cookie_name", "cookie_value", max_age=3600)
  2. Get cookie. Get the cookie through request.cookies, it returns a dictionary object, you can get the corresponding value in the dictionary.
    # Get request cookies.
    cookies = request.cookies
    
    # Get cookie value by cookie name.
    cookie_value = cookies.get("cookie_name")
  3. Remove cookie. Delete cookie use HTTP response object’s deleting_cookie(cookie_name) method. The deletion here just makes the cookie expire, not really delete the cookie.
    # Get http response object.
    resp = make_response("del success")
    
    # Invoke delete_cookie() method to delete a cookie by cookie name.
    resp.delete_cookie("cookie_name")
  4. Flask Manage Cookie Example Source Code.
    # Import Flask, make_response, request package.
    from flask import Flask, make_response, request
    
    app = Flask(__name__)
    
    # Add /set_cookie url route.
    @app.route("/set_cookie")
    def set_cookie(c_1, p_1, c_2, p_2, c_3, p_3):
      resp = make_response("success")
      '''
        Set cookie, the default cookie is a temporary cookie which will expire when web browser close.
      '''
      resp.set_cookie(c_1, p_1)
      resp.set_cookie(c_2, p_2)
    
      # Set cookie expiration time in 3600 seconds through max_age cookie attribute.
      resp.set_cookie(c_3, p_3, max_age=3600)
      return resp
     
    # Add /get_cookie url route.
    @app.route("/get_cookie")
    def get_cookie(cookie_name):
      """
        Get a cookie through request.cookies. It will return a dictionary object.
      """
      cookie_value = request.cookies.get(cookie_name) 
      return cookie_value
     
    # Add /delete_cookie url route.
    @app.route("/delete_cookie")
    def delete_cookie(cookie_name):
      """
        Remove cookie by HTTP response object's delete_cookie(cookie_name) method. It just make the cookie expire not really remove the cookie.
      """
      # Get http response object.
      resp = make_response("del success")
    
      # Remove the cookie by invoking the delete_cookie() method.
      resp.delete_cookie(cookie_name)
      return resp
     
    if __name__ == '__main__':
      app.run(debug=True)

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky