The use of the session

In Flask, session is usually used to set the permissions of certain pages. For example, some pages must be logged in to be seen, and the login information or flags are stored in the session. Its use process is as follows:

  1. Add app.config[‘SECRET_KEY’] = ‘you never guess’ to the entire Flask project startup file,SECRET_KEY is used to encrypt sessions, essentially an encryption salt.
  2. Add from Functools import Wraps to the used py file
  3. Add from Flask Import Session to the py file you use
  4. And then we write our handler
  5. Write the log-in flag or store other information about the request in the logical code
  6. Finally, add a qualifier for the limiting function before the view function that sets the limiting

A simple example

# encoding: utf-8 from flask import Flask from flask import request, session, Redirect from functools import wraps app = Flask(__name__) app.config['SECRET_KEY'] = 'you never guess' # Use session Def wrap (fn): @wraps(fn) def wrapper(*args, **kwargs): User = session.get('logged_in', None) # get the login flag if user: Return fn(*args, **kwargs) # return 'need login! Return wrapper @app.route('/') @app.route('/home') def index(): session["global_name"] = "global_path" return session["global_name"] + 'home.html' @app.route('/find') def find(): print(vars(session)) return session.get("global_name", "None") + 'find.html' @app.route('/doc') @authorize # Indicates that the view page must be logged in to access def blog(): Print (session['username']) return 'blog.html' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return "login.html" if request.method == 'POST': username = request.values.get('username') password = request.values.get('password') if username and password: Session ['username'] = username session['password'] = password return username + password else: Return "need username and password" @app.route('/signout', methods=['GET', 'POST']) @authorize (): Return redirect('/home') if __name__ == '__main__': app.run() return redirect('/home') if __name__ == '__main__': app.run()Copy the code

A few words of curl

# login interface and return, we can see that the response of the set - cookies curl -x POST "http://127.0.0.1:5000/login" 3-d "username = test&password = 123" HTTP / 1.0 200 OK Set-Cookie: session=eyJsb2dnZWRfaW4iOnRydWUsInBhc3N3b3JkIjoiMTIzIiwidXNlcm5hbWUiOiJsZ2oifQ.DoNGjg.4c2Adke_tzqo5MW_BHs95FvY6i4; HttpOnly; Path = / # interface without cookies access need to log in to the curl "http://127.0.0.1:5000/doc" need signin! Curl --cookie "session=eyJsb2dnZWRfaW4iOnRydWUsInBhc3N3b3JkIjoiMTIzIiwidXNlcm5hbWUiOiJsZ2oifQ.DoNGjg.4c2Adke_tzqo5MW_BHs95FvY6i4" "Http://127.0.0.1:5000/doc" user/blog. HTML # logout interface is same as above. The curl "http://127.0.0.1:5000/logout" need signin! curl --cookie "session=eyJsb2dnZWRfaW4iOnRydWUsInBhc3N3b3JkIjoiMTIzIiwidXNlcm5hbWUiOiJsZ2oifQ.DoNGjg.4c2Adke_tzqo5MW_BHs95FvY6i4" "Http://127.0.0.1:5000/signout" <! DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting... DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting... </title> <h1>Redirecting... </h1> <p>You should be redirected automatically to target URL: Curl -v "http://127.0.0.1:5000" <a href="/home">/home</a>. Global_pathhome.html HTTP/1.0 200 OK set-cookie: session=eyJnbG9iYWxfbmFtZSI6eyIgYiI6IloyeHZZbUZzWDNCaGRHZz0ifX0.DoNPag.ooEMHsinZlKRQpLF_-S3axsH3jc; HttpOnly; Path = / # set global_name want, do not bring the curl of the cookie is not "http://127.0.0.1:5000/find" Nonefind. HTML # with cookies curl, cookies "session=eyJnbG9iYWxfbmFtZSI6eyIgYiI6IloyeHZZbUZzWDNCaGRHZz0ifX0.DoNPag.ooEMHsinZlKRQpLF_-S3axsH3jc" "Http://127.0.0.1:5000/find" global_pathfind. HTML # setting cookies curl -v "http://127.0.0.1:5000/set_cookie" < HTTP / 1.0 200 OK < Set-Cookie: name=test; Expires=Wed, 19-Sep-2018 03:42:31 GMT; Max-Age=200; Path=/ < Set-Cookie: age=18; Closing connection 0 # Retrieve cookie curl --cookie "name=test; The age 18 = "" http://127.0.0.1:5000/get_cookie" name is test, the name is 18Copy the code

Conclusion:

Using curl, it is difficult to notice the difference between cookie and session. Using curl without a cookie will result in an error, which is why a session is dependent on a cookie.

  1. Cookie exists for:

    Because HTTP is a stateless protocol, it does not track requests from one client to another. This means that even after the first connection to the server and successful login, the second request server still does not know which user is requested. Therefore, cookies are used to solve this problem: after the first successful login, the server returns a cookie to the browser, and the browser saves the cookie locally. When the user sends a second request, the cookie data stored in the last request will be automatically carried to the server, and the server will determine the user according to the cookie data.

  2. Session and cookie serve a similar function: They are also used to store user-related information on the server. The encrypted user information is stored in the session and a unique session_ID is generated.

  3. A combination of cookies and sessions

    Generally, there are two storage methods:

    (1) Stored on the server side: store a session_ID through the cookie, and then the specific data is stored in the session. If the user has logged in, the server will save a session_ID in the cookie, and carry the session_ID in the next request. According to the session_ID, the server will obtain the user's session data from the session library, and then know who the user is. (2) Stored in the client: The session data is encrypted and stored in cookies. The technical term for this is the Client Side Session. The Flask framework takes this approach, but can be replaced with something else.Copy the code

Flask session mechanism

The user information is encrypted into the session, and then the session is stored in the cookie. On the next request, the session is read from the cookie sent by the browser, and then data is read from the session and decrypted to obtain the final user data. This saves server overhead.

The deletion of the cookie

@app.route('/del_cookie') def del_cookie(): @app.route('/del_cookie') def del_cookie(): Response =make_response('delete cookie') Response.set_cookie ('Name','',expires=0) return response(3 @app.route('/del_cookie2') def del_cookie2(): response=make_response('delete cookie2') response.delete_cookie('Name') return responseCopy the code

Additional properties of the cookie

Watch “the Set – cookies: name = test; Expires=Wed, 19-Sep-2018 03:42:31 GMT; Max-Age=200; Path=/” Cookie has many attributes:

You can see cookie information in the Resources TAB of the Chrome console. There may be many cookie objects under a domain name. The name field is the name of a cookie. The value field is the value of a cookie. The domain field is the domain name from which this cookie can be accessed. For a non-top-level domain name, such as a second-level domain name or a third-level domain name, the domain of the cookie can only be a top-level domain name or a second-level domain name or a third-level domain name. Cookies of other second-level domain names cannot be set; otherwise, cookies cannot be generated. Top-level domain The domain can only be a top-level domain, but cannot be a second-level domain or a third-level domain. Otherwise, cookies cannot be generated. A second-level domain name can read cookies of a top-level domain name or its own domain, but cannot read cookies of other second-level domain names. Therefore, to share cookies among multiple secondary domain names, you need to set the domain to the top-level domain, so that all secondary domain names or the value of this cookie. A top-level domain can only obtain the cookie of a top-level domain. Other domains whose domains are set to second-level cannot be obtained. The path field is the page path from which this cookie can be accessed. For example, if domain is abc.com and path is /test, only pages under /test can read the cookie. The Expires/max-age field specifies the timeout period for this cookie. If the value is set to a time, the cookie becomes invalid when the time is reached. If this parameter is not set, the default value is Session, which means that the cookie will expire with the Session. This cookie expires when the browser closes (not the browser TAB, but the entire browser). Size field The Size of this cookie. The HTTPonly property of the HTTP field cookie. If this property is true, the cookie is only contained in the HTTP request header and cannot be accessed through document.cookie. The Secure field sets whether this cookie can only be passed over HTTPSCopy the code

Here are the configuration items for the cookie attribute in flask

SECRET_KEY Key SESSION_COOKIE_NAME Session cookie name SESSION_COOKIE_DOMAIN Session cookie domain. If not set, cookies will be valid for all subdomains of SERVER_NAME. SESSION_COOKIE_PATH Path of the session cookie. If not set or not set for '/', the cookie will be valid for all APPLICATION_ROOT. SESSION_COOKIE_HTTPONLY controls whether cookies should be set to the httponly flag, which defaults to True. SESSION_COOKIE_SECURE controls whether cookies should be set to a security flag. The default is False.Copy the code

extension

  1. Since sessions rely on cookies, how can they maintain state if the browser disables cookies? In this case, it is necessary to use URL rewriting, which makes the server receive each request parameter with sessioinId, that is, from the original implicit (headers) parameter to URL or body parameter.

  2. Does the session disappear when we empty the browser? This question contains some pitfalls. Because most of the time when you clear the browser, you actually need to log in again, so it’s natural for many people to assume that clearing the browser cache (including cookies) will make the session disappear. In fact, this conclusion is wrong. You know, the session exists on the server, you clear the browser cache, you just clear the cookie, it has nothing to do with the session. So why can’t we access the site and need to log in again? Because the browser cache is cleared, there must be no JSESSIONID cookie in the cookie array. Therefore, we must create a new session and use the new sessionId to assign a value to the JSESSIONID cookie. Because it is a new session, there must be no attribute value such as userId in the session. Therefore, the judgment result is empty and you need to log in again. After this assignment, the next time the site is requested, because the cookie array already has the JSESSIONID cookie, and the corresponding session can be found by the value of the JSESSIONID, so there is no need to log in again.

reference

  1. http://www.pythondoc.com/flask/config.html
  2. https://blog.csdn.net/qq_37526590/article/details/80219227
  3. https://www.cnblogs.com/keyi/p/6823853.html