catalogue
You need to set the secret key before storing the session
Before being accessed for the first time, the hook function
Hook function before each access
After each access, the hook function
The result function is executed whether there is an exception or not
1, State retention
Here we use two methods to maintain the state.
cookie,session
1. HTTP protocol
Stateless,
In order to solve this stateless problem, state preserving is introduced.
State keeping is to realize some connection between requests through tools -- resource sharing
2. cookie status hold
-
Set cookie return
from flask import Flask from flask import request from flask import make_response app = Flask(__name__) @app.route('/login', methods=["POST"]) def do_login(): username = request.form.get("username") password = request.form.get("password") if username == "Tom" and password == "123": # The account password is verified and the login is successful resp = make_response("<h1>Login succeeded!</h1>") resp.set_cookie("username", username) # cookie return return resp else: return "<h1>Login failed!</h1>" @app.route("/comment") def do_comment(): return "<h1>Comment success!</h1>" if __name__ == '__main__': app.run()
result:
-
Save Cookies
Get cookie
from flask import jsonify @app.route("/comment") def do_comment(): # You can't comment until you sign in username = request.cookies.get("username") # Get Cookie if not username: return jsonify({"msg": "No login, login in comments first"}) return jsonify({"msg": "Comment success!"})
result
-
not saved
-
Saved
- State timing removal
3. session state hold
The status of the cookie is stored to the client
Insecure, small amount of data stored in cookie s
We hope that it can be stored on the server side. At this time, we can use the session mechanism.
Different browsers correspond to different sessions, and each session has a unique SID
-
Store data in session
-
You need to set the secret key before storing the session
from flask import Flask from flask import request from flask import make_response from flask import session app = Flask(__name__) # Before using session, you need to configure the key secret_key app.config["SECRET_KEY"] = "1234567890abcdefg" @app.route('/login', methods=["POST"]) def do_login(): username = request.form.get("username") password = request.form.get("password") if username == "Tom" and password == "123": session["username"] = username resp = make_response("<h1>Login succeeded!</h1>") return resp else: return "<h1>Login failed!</h1>" if __name__ == '__main__': app.run()
result
After we save the session, the session will automatically write a cookie in the response response by default. The key is the session, and the value is the ID of the session
from flask import Flask from flask import request from flask import make_response from flask import jsonify from flask import session app = Flask(__name__) @app.route('/login', methods=["POST"]) def do_login(): username = request.form.get("username") password = request.form.get("password") if username == "Liu Bei" and password == "123": session["username"] = username resp = make_response("<h1>Login succeeded!</h1>") return resp else: return "<h1>Login failed!</h1>" if __name__ == '__main__': app.run()
result
Flash will obtain the session ID according to the obtained session cookie, and then find the session cache according to the SID, and then find the previously stored data.
from flask import Flask from flask import request from flask import make_response from flask import jsonify from flask import session app = Flask(__name__) @app.route("/comment") def do_comment(): # You can't comment until you sign in username = request.cookies.get("username") if not username: return jsonify({"msg": "No login, login in comments first"}) return jsonify({"msg": "Comment succeeded:{}".format(username)}) if __name__ == '__main__': app.run()
result:
4. Exception handling
abort can interrupt and throw an exception
The exception thrown by abort is the HTTP status code
from flask import abort @app.route("/error") def do_error(): abort(500) return "<h1>I'm soldier Zhang GA</h1>"
For the exception return of HTTP status code, we can customize it
-
Custom 500
@app.errorhandler(500) def handler_500_error(error): return "<h1>Server error, please contact the administrator. The administrator's phone number is 1111</h1>"
-
Custom 404
@app.errorhandler(404) def handler_404_error(error): return "<h1>I can't find my way home<h1>"
The exception return information of 500 response code and 404 response code is customized
If it is a 500 error, a < H1 > server error is returned. Please contact the administrator < H1 >
If it is a 404 error, it returns < H1 > I can't find my way home < H1 >
5. Hook function
@app.route('/login', methods=["POST"]) def do_login(): username = request.form.get("username") password = request.form.get("password") if username == "Liu Bei" and password == "123": # The account password is verified and the login is successful # resp = make_ Response ("< H1 > login succeeded! < / H1 >") # resp.set_cookie("username", username) abort(500) session["username"] = username resp = make_response("<h1>Login succeeded!</h1>") return resp else: return "<h1>Login failed!</h1>" @app.route("/error") def do_error(): return "<h1>I'm soldier Zhang GA</h1>" @app.before_first_request def func1(): print("before_first_request") @app.before_request def func2(): print("before_request") @app.after_request def func3(resp): print(resp) print("after_request") return resp @app.teardown_request def func4(error): print(error) print("teardown_request") return error
result:
-
Before being accessed for the first time, the hook function
before_first_request
-
Hook function before each access
before_request
-
After each access, the hook function
after_request
-
The result function is executed whether there is an exception or not
teardown_request
To be effective, it must be non debug mode
Case 2: using cookie s to maintain login status
Extension 1: when the same browser on a computer accesses the same website, it will use the same cookie and session
Extension 2: cookie and session area