This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.

The use of cookies

What is a Cookie

As we all know, HTTP protocol is stateless, that is, after a request and response, the server will not retain any state information of the other party. For some information to be retained, Cookie technology can be used to complete, by adding Cookie data in the request and response packets to save the state information of the client.

Web server to store some data (such as user information) and preserve the small text data on the browser, the browser will save it in a certain time, at the next sends a request to the server with these data, a Cookie is often used to manage the user session state (such as user login), save the user some information.

Use cookies in Flask

In Flask, if you want to add a cookie to the response, you use the set_cookie() method of the Response object.

The set_ cookie() method takes the following parameters:

  • Key: indicates the cookie key name
  • Value: the cookie value
  • Max_age: indicates the time for the cookie to be saved, in seconds
  • Expires: Specifies the expiration date
  • Path: limits the available path for cookies. Default is the entire domain name
  • Domain: indicates the domain name of the cookie
  • Secure: This parameter is set to True and can be used only through HTTPS
  • Httponly: set to True to prevent client JS from obtaining cookies

Specific use is as follows:

@app.route('user/<name>')
def user(name) :
    response = make_response('hello {}'.format(name), 200)
    response.set_cookie("name", name)
    return response
Copy the code

In Flask, cookies can be obtained via the Request request object cookies property.

@app.route('/hello')
def hello() :
    user = request.args.get('name')
    if not user:
        user = request.cookies.get("name".'default')
    return 'Hello {}! '.format(user)
Copy the code

The use of the session

What is a session

A session is a user session that can be used to store some state of the current request so that information can be shared before a request is made. Session is stored on the server and is distinguished by a unique identifier, namely, the session ID. Generally, the session ID is stored in cookies. The server can obtain the session ID in the Cookie to obtain the user session.

Flask session objects

We have learned that the most important function of Cookie is to save the state information of the client user. However, there is such a problem that cookies are stored on the client and can be easily added and modified in the browser. Moreover, if the user’s state information is stored in cookies in plain text, then the user information of others can be forged by forging Cookie information. To get some permissions. To avoid this problem, we encrypt the sensitive Cookie content. Flask provides session objects that are used to encrypt and store Cookie data.

Use sessions in Flask

Session needs to use the key to sign data to encrypt data. Therefore, you need to set a key app.secret_key first. The key set here is only a simple example.

# set key
app.secret_key = 'qwertyuiop'


@app.route('/user', methods=['POST'.'GET'])
def user() :
    if request.method == 'POST':
        user = request.form['user_name']
        session['user_name'] = request.form['user_name']
        return 'Hello {}! '.format(user)
    else:
        if 'user_name' in session:
            return 'Hello {}! '.format(session["user_name"])
Copy the code

The session object is used just like a dictionary. As shown above, after a user logs in using POST, the user name is saved in the session. The next time a GET request is made, the user’s information can be obtained from the session without passing any information.

To clear session specific information, such as the user name, use session.pop(“user_name”, None) or session.clear() to clear all.

Original is not easy, if small partners feel helpful, please click a “like” and then go ~

Finally, thank my girlfriend for her tolerance, understanding and support in work and life!