Hardware and software Environment
- Windows 10 64bit
- Anaconda3 with python 3.7
- PyCharm 2019.3
- Flask 1.1.1
The Cookie and Session
What is a Cookie
Cookie is a mechanism for the client to save user information, which is used to record some information about the user. In fact, a Cookie is a small piece of text that the server stores on the local machine and sends to the server with each request. The interaction between the client and server is shown below
Cookie instance
In Flask, the response body is built with the make_response of the Flask object, and then the cookie is set with set_cookie, which is key-value pair data. Here is a simple example of a Cookie
Run. Py File contents
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/cookie', methods=['GET'])
def cookie() :
resp = make_response("<html><body>Cookie</body></html>")
resp.set_cookie('name'.'waws')
return resp
if __name__ == '__main__':
app.run(host="127.0.0.1",port=5000,debug=True)
Copy the code
Start the Flask after service, visit http://127.0.0.1:5000/cookie
Here is a recommended Chrome browser Cookie plug-in, it can be very convenient to view, modify, delete Cookie information.
In this example we see Cookie information stored locally in the Flask server setting (‘name’ : ‘waws’)
What is a Session
The Session is very similar to the Cookie mentioned above, except that the Session is stored on the server. In actual scenarios, login failures are often encountered because the Session is in effect.
The Session instance
In Flask, session objects are used to hold key-value pairs. Note that using Session requires app.secret_key to be set. Consider the following example
Run. Py File contents
from flask import Flask, render_template, make_response, session
app = Flask(__name__)
app.secret_key = "test"
@app.route('/session', methods=['GET'])
def sess() :
resp = make_response("<html><body>Session.<a href='/getValue'>Get Value</a></body></html>")
session['name'] = 'waws'
return resp
@app.route('/getValue')
def getValue() :
if 'name' in session:
name = session['name']
return render_template('getvalue.html', name=name)
if __name__ == '__main__':
app.run(host="127.0.0.1",port=5000,debug=True)
Copy the code
Go to the template file, getValue.html file content
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GetValue</title>
</head>
<body>
<p>Session value: <b> {{ name }} </b> </p>
</body>
</html>
Copy the code
Start the Flask services, visit http://127.0.0.1:5000/session
Click on the hyperlink to go to the getValue.html page