Flask-cookie usage

When a user accesses the server for the first time using a browser, the server generates cookies and returns them in response and saves them in the user’s browser.

from flask import Flask,[email protected]('/set/<name>')def set_cookie(name): response = make_response(redirect(url_for('hello'))) response.set_cookie('name',name) # The set_cookie view creates a set-cookie field in the generated response header, that is, "set-cookie: name= XXX; Path=/" return responseCopy the code

The next time a user accesses the same server, the cookie is stored in the header.

from flask import Flask,[email protected]('/')@app.route('/hello')def hello(): Name = request.args. Get ('name') # select * from cookie if name is None: Name = request.cookies. Get ('name','Human') # return '<h1>Hello,%s</h1>' % nameCopy the code

Because users can directly modify the browser’s cookie value and impersonate others’ accounts, it is not safe to directly use cookies.

Flask provides session objects for storing encrypted Cookie data (by default, it stores the data in a browser Cookie named Session).

App.secret_key = ‘secret string’ # Set the key

It is safer to write the key into a system environment variable (using export or set on the command line), or to save it in an. Env file

SECRET_KEY=secret string

Then use the getenv() method provided by the OS module in the program script to obtain:

App.secret_key = os.getenv(‘ secret_key ‘,’secret String ‘) # The second argument is used as the default value when no corresponding environment variable is obtained

@app.route('/login')def login(): session['logged_in'] = True Add a cookie named logged_in to the session and set its value to True. # When adding a cookie to the session object, the data is signed using the program's key and stored in a cookie named session. Users can view the encrypted value but cannot modify it. Once the data is modified, the value of the signature is also changed. In this way, the read authentication fails and the corresponding session value is invalid redirect(url_for('hello'))@app.route('/hello')def hello(): name = request.args.get('name') if name is None: name = request.cookies.get('name','Human') response = '<h1>Hello, %s! </h1>' % name #session data can be read by key like a dictionary, or by get(). Response += '[Authenticated]' else: Response += '[Not Authenticated]' return responseCopy the code

To log out of a user’s account, the actual operation is to delete the logged_in cookie, which represents the user’s authentication, through the pop method of the session object.

from flask import [email protected]('/logout')def logout():  if 'logged_in' in session:    session.pop('logged_in')  return redirect(url_for('hello'))
Copy the code

By default,session cookies are deleted when the user closes the browser.

By setting the session.permanent property to True, you can extend the validity of a session to the datetime.timedelta object corresponding to the flask.permanent_session_lifetime property value.

PERMANENT_SESSION_LIFETIME can also be set. The default value is 31 days.

Although the session object will sign and encrypt the Cookie, this method only ensures that the session content will not be tampered with, and the encrypted data can still be easily read by tools (even without knowing the key). Therefore, sensitive information such as user passwords cannot be stored in the session.

! [Flask – the use of cookies] (https://p6-tt.byteimg.com/large/pgc-image/22e89eef4be142dea58f059c87eff884?from=pc)