当前位置:网站首页>[flask] response, session and message flashing
[flask] response, session and message flashing
2022-07-06 01:27:00 【Coriander Chrysanthemum】
Preface article :
- 【Flask】Web Departure and implementation are based on Flask The smallest application
- 【Flask】 Static file and template rendering
- 【Flask】 Get request information 、 Redirect 、 Error handling
Respond to Response
The view function ( Request to process the corresponding function ) The return value of will be automatically converted into a response object for you . If the return value is a string , It will be converted into a response object , Where the string is the response body , One 200 OK Status code and a text/html mimetype. If the return value is a dict Data of type , We need to borrow jsonify() To create a response.Flask The logic applied to convert the return value into a response object is as follows :
- If the correct type of response object is returned , Return directly from the view .
- If it's a string , Then use this data and default parameters to create a response object .
- If it is dict, Then use
jsonifyCreate a response object . - If a tuple is returned , Then the items in the tuple can provide additional information . Such tuples must use (response, status)、(response, headers) or (response, status, headers) In the form of .
statusThe status code will be overwritten , alsoheadersIt can be a list or dictionary with additional header values . - If none of this works ,Flask It will be assumed that the return value is valid WSGI Application and convert it into a response object .
If you want to get the result response object in the view , have access to make_response() function .
Suppose we have the following view :
from flask import render_template
@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
You just need to use make_response() Wrap the return expression and get the response object to modify it , Then go back to it :
from flask import make_response
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp
JSON Type of API
In the development of front and back separation , Most of the data interaction methods are using json Format data as a medium . Use Flask It's easy to start writing such API. If you return from the view dict, It will be converted to JSON Respond to .
@app.route("/me")
def me_api():
user = get_current_user()
return {
"username": user.username,
"theme": user.theme,
"image": url_for("user_image", filename=user.image),
}
According to your API Design , You may wish for dict Create a type other than JSON Respond to . under these circumstances , Use jsonify() function , It will serialize any supported JSON data type . Or check out support for more complex applications Flask Community expansion .
from flask import jsonify
@app.route("/users")
def users_api():
users = get_all_users()
return jsonify([user.to_json() for user in users])
session
In addition to the request object , There's another one called session The object of , It allows you to store user specific information from one request to the next . This is cookie Above for you , And encrypt cookie To sign . This means that users can view your cookie But you can't modify it , Unless they know the key used for signing .
In order to use session, You must set a key . Here is how the conversation works :
from flask import session
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
if 'username' in session:
return f'Logged in as {
session["username"]}'
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> '''
@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))
How to generate a good key : The key should be as random as possible . Your operating system has a way to generate fairly random data based on an encrypted random generator . Use the following command to quickly generate Flask.secret_key( or SECRET_KEY) Value :
python -c 'import secrets; print(secrets.token_hex())'
# '192b9bdd22ab9ed4d12e236c78afcb9a393ec15f71bbf5dc987d54727823bcbf'
On the based on cookie Description of the conversation :Flask Will get the values you put into the session object and serialize them as cookie. If you find that some values will not persist in the request , It does enable cookie, And you don't receive a clear error message , Please check the page response cookie The size and Web Compared with the size supported by the browser .
In addition to the default client based session , If you want to handle the session on the server side , There are several Flask The extension supports this .
Message Flashing
Good applications and user interfaces are all about feedback . If users don't get enough feedback , They may end up hating the application .Flask Provides a very simple method , Feedback can be provided to the user through the flashing system . The blinking system can basically record a message at the end of the request and at the next ( And just next ) Access it on request . This is usually combined with layout templates to expose messages .
To flash a message , Please use flash() Method , To get information , You can use the get_flashed_messages().
边栏推荐
- 干货!通过软硬件协同设计加速稀疏神经网络
- Leetcode sword finger offer 59 - ii Maximum value of queue
- Force buckle 1020 Number of enclaves
- 【Flask】获取请求信息、重定向、错误处理
- Introduction to robotics I. spatial transformation (1) posture, transformation
- Distributed base theory
- 【SSRF-01】服务器端请求伪造漏洞原理及利用实例
- Leetcode skimming questions_ Sum of squares
- 【Flask】官方教程(Tutorial)-part2:蓝图-视图、模板、静态文件
- A picture to understand! Why did the school teach you coding but still not
猜你喜欢

Unity | two ways to realize facial drive

【Flask】官方教程(Tutorial)-part3:blog蓝图、项目可安装化

MATLB | real time opportunity constrained decision making and its application in power system

关于softmax函数的见解

Pbootcms plug-in automatically collects fake original free plug-ins

JVM_ 15_ Concepts related to garbage collection

ORA-00030
![[技术发展-28]:信息通信网大全、新的技术形态、信息通信行业高质量发展概览](/img/94/05b2ff62a8a11340cc94c69645db73.png)
[技术发展-28]:信息通信网大全、新的技术形态、信息通信行业高质量发展概览

Xunrui CMS plug-in automatically collects fake original free plug-ins

一图看懂!为什么学校教了你Coding但还是不会的原因...
随机推荐
[detailed] several ways to quickly realize object mapping
Leetcode 208. Implement trie (prefix tree)
Maya hollowed out modeling
Opinions on softmax function
How does the crystal oscillator vibrate?
2022 Guangxi Autonomous Region secondary vocational group "Cyberspace Security" competition and its analysis (super detailed)
How does Huawei enable debug and how to make an image port
In the era of industrial Internet, we will achieve enough development by relying on large industrial categories
A Cooperative Approach to Particle Swarm Optimization
Docker compose配置MySQL并实现远程连接
【详细】快速实现对象映射的几种方式
Distributed base theory
[pat (basic level) practice] - [simple mathematics] 1062 simplest fraction
GNSS terminology
Leetcode daily question solution: 1189 Maximum number of "balloons"
Vulhub vulnerability recurrence 74_ Wordpress
FFT learning notes (I think it is detailed)
WGet: command line download tool
leetcode刷题_验证回文字符串 Ⅱ
Basic process and testing idea of interface automation