Pre-knowledge:
1.http is a stateless communication protocol, the communication state is not saved in itself
Responsible for requesting (request) the server receives a user's 2.web essentially according to the rules and give the user a response (response)
3. Session (session) is a web server used to manage the user a way, in their own web server that all communications are carried out with the same user session time
4.cookie is a way of implementing session
Then entered, reference documentation: the Flask official documents
For convenience directly demo code provided by the official, only the login function is modified, print session content After adding the session
1 @app.route('/login', methods=['GET', 'POST']) 2 def login(): 3 if request.method == 'POST': 4 session['username'] = request.form['username'] 5 print(session) 6 return redirect(url_for('index')) 7 return ''' 8 <form action="" method="post"> 9 <p><input type=text name=username> 10 <p><input type=submit value=Login> 11 </form> 12 '''
The following is the actual run-time analysis of results
1. Direct access to the site, the display is not logged in
2. Access / login, login is completed
Page shows
Server Display
Observe http protocol package
Request packet follows
Submitted a form with the post method up
Response is as follows
Server set a cookie, and gives a 302 redirect response back to the redirection path '/'
At this time the browser requests a new direct route, the following request packet
He has been put on cookie
Server response following
A normal response 200
3. Access logout
Access logout, the browser displays
View request packet
Normally carry a cookie request
View response packet
Also given a 302 redirect, but also had a cookie is set, but this time directly to the cookie set to null
Redirected communications below
At this time, the browser sends a request already not a cookie
4. Use a different browser access
Then use ie browser chrome browser and access
chrome visit the following results
Server is shown below
Then use ie browser to access
Server Display
Two browsers share of the cookie by contrast is not as visible, then refresh the page chrome is still using chrome display user login
Modifying the index function, it is possible to print the value of the session
1 @app.route('/') 2 def index(): 3 if 'username' in session: 4 print(session) 5 return 'Logged in as %s' % escape(session['username']) 6 return 'You are not logged in'
刷新chrome与ie
由此可见session与cookie有关,根据不同的cookie服务器对session的判断也不同
这里提供一份flask的源码解析博客
其中指出flask的会话管理完全依赖cookie执行,服务器本身不保存相关数据,放到cookie中交给客户端保存
当客户端提交cookie时,服务器从cookie中解析出session,完成会话。
这就是flask默认提供的session功能,如果需要更加安全地将session保存到服务器,则需要使用flask-session库