Hello everyone, I am python222_Feng, and I have recently updated the Flask3 series course on Python Web development. Thank you for your support.
Update address on Bilibili:
https://www.bilibili.com/video/BV1XGwXeYEYY/
Click the public account card γPython222γ below,
Reply: 888,
ππ to get Feng's Python video package download ππ
πππClick the card above
Reply '888' to get it
Response formats in HTTP responses can be transmitted in various formats. In most cases, we use HTML format, which is also the default setting in Flask. In specific situations, we may use other formats. Different response data formats require different MIME types, which are defined in the Content-Type field of the header. Taking the default HTML type as an example:
content-type: text/html; charset=utf-8
Common data formats include plain text, HTML, and JSON format.
Let's look at an example of plain text type:
@app.route('/plain')
def plain():
response = make_response('<p>Hello, Python222οΌ</p>')
response.mimetype = 'text/plain'
return response
Now let's look at an HTML example for comparison:
@app.route('/html')
def html():
response = make_response('<p>Hello python222!</p>')
response.mimetype = 'text/html'
return response
Finally, let's look at a JSON example. When we perform AJAX asynchronous requests, the backend returns data in JSON format.
@app.route('/ajax')
def ajax():
data = {
'name': 'Xiao Feng',
'site': 'www.python222.com'
}
response = make_response(json.dumps(data))
response.mimetype = 'application/json'
return response
Of course, Flask provides a convenient way to return JSON data using the jsonify method.
@app.route('/ajax2')
def ajax2():
return jsonify(name='Xiao Feng 2', site='www.python222.com')
Client state information cookies and encryption HTTP is a stateless protocol. This means that after a request-response cycle ends, the server does not retain any information about the state of the other party. However, for certain web applications, some client information must be remembered, such as the user's login status, so that different responses can be returned based on the user's state. To solve this problem, cookie technology was developed. Cookie technology saves client state information by adding cookie data to the request and response messages. A cookie is essentially a small piece of text data stored in the client's browser.
We can use the set_cookie() method of the response object to add cookies. The parameters of the set_cookie() method are:
- key: the key (name) of the cookie
- value: the value of the cookie
- max_age: the time the cookie is saved, in seconds; defaults to expiration at the end of the user session (i.e., when the browser is closed)
- expires: the specific expiration time, a datetime object or UNIX timestamp
- path: restricts the cookie to be available only on the given path, defaults to the entire domain
- domain: sets the domain where the cookie is valid
- secure: if set to True, the cookie can only be used via HTTPS
- httponly: if set to True, it prevents client-side JavaScript from accessing the cookie
Example:
@app.route('/cookie')
def set_cookie():
response = make_response()
response.set_cookie('username', 'jack')
return response
So how do we retrieve cookies from the browser client?
We can use the get() method of the cookies attribute of the request object:
@app.route('/getcookie')
def get_cookie():
return request.cookies.get('username')
However, we find a problem: storing data in plaintext in the client's browser can easily lead to data theft and leakage. It is not secure.
Therefore, it is necessary to encrypt the data. Flask provides the session object to implement cookie encryption.
First, we set a secret key, which can be a random string; the more complex, the safer.
# Set secret key
app.secret_key = 'ljfda32@2334_ss' Then we can directly use the session object to store cookies:
@app.route('/cookie')
def set_cookie():
# response = make_response()
# response.set_cookie('username', 'jack')
session['password'] = 123456
return 'ok'
Retrieving cookie code example:
@app.route('/getcookie2')
def get_cookie2():
print('username:', session['password'])
return 'ok'
Click the public account card γPython222γ below,
Reply: 888,
ππ to get Feng's Python video package download ππ
πππClick the card above
Reply '888' to get it