Python Flask Request Data Acquisition Response Detailed Explanation
- 2021-12-11 08:22:15
- OfStack
Directory 1, Request Data and Its Acquisition 1.1 Request Related Data 1.2 Fixed Parameters and Converter 1.3 Query Parameters Acquisition 1.4 Form Data Acquisition 1.5 File Upload 1.6 Other Request Parameters 2, New Book of Response Data 3 Set 2.1 String Response Format 2.2 Template Response Format 2.3 Redirect Response Format 3, Response json Data and Tuple Data 3.1 json Data Response 3.2 Tuple Data Response 4, make_response () Custom Response Summary
1. Request data and its acquisition
1.1 Request relevant data
# Request parameter
Request parameters for the client 1 Exist in general 3 Place
1 Request body
2 Request header
3 , URL Parameter
1). National parameter
2). Query string
# The following table carries parameters for request parameters :
序号 | 参数或信息 | 解释 |
1 | 固定参数 | URL的组成部分,不可缺失 |
2 | 查询字符串:args | 根据需求,可有可无 |
3 | 表单数据 | 提交form表单是传递的数据 |
4 | 文件上传:files | 用户向服务器上传的文件 |
5 | 请求头:headers | 请求头中携带的请求信息 |
6 | 请求方法:method | 请求所使用的请求方法 |
7 | URL地址:url | 请求的URL地址 |
1.2 Fixed Parameters and Converters
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
#1 Fixed parameters
Fixed parameters refer to the URL Fixed in, is not available 1 Part, the difference with query string, query string is optional
Fixed parameter :
/article/1: If 1 As an article id Is not available 1 Part
/art/1?title=" Decorator ":title Follow ? Followed by the query string
#2. Obtaining request parameters
#(1). Grammatical form :
@app.route('/users/<user_id>')
def user_info(user_id):
return ' Obtained userid For :{}'.format(user_id)
#(2). Grammatical explanation:
Use in routing <user_id> To receive fixed parameters, and don't forget to pass the view, that is, the view must define formal parameters user_id.
Attention :
- In the route user_id You can limit the type before, and refer to the writing method: <int:user_id>, If the type is limited, the fixed parameters transmitted from the front end must meet the type requirements, otherwise an error will be reported ; If the type is not qualified, it is received as a string type by default
- The view must define a parameter, and the name of the parameter must be the same as that in the route 1 Straight, that is, write in the route user_id The view function parameter must also be user_id
#3. Converter
The above fixed parameters are implemented using converters, flask The converter that comes with it has a total of 6 A :
- UnicodeConverter: String converter
- AnyConverter: Matching any Any path in, written: '/users/<any(xxx,yyy):user_id>'
- PathConverter: Path converter, similar to string converter, but the parameters can include "/"
- IntergerConverter: Shaping converter
- FloatConverter: Floating point converter
- UUIDConverter : UUID Only 1 Identification code converter
#4. Custom converter
If flask Built-in converter can not meet specific needs, you can customize the converter, custom converter can participate in the implementation of source code
#(1). Custom Converter Steps
- Custom converter class: inherits from BaseConverter, Specify regular matching rules internally
- Add a custom converter class to the converter container specified
- Using a custom converter
#(2). Custom Converter Instance
# Import BaseConverter
from werkzaug.routing import BaseConverter
# Customize Converter Class
calss phoneConverter(BaseConverter):
regex = r'1[3-9]\d{9}'
# Add to Converter Container
app.url_map.converters['phone'] = phoneConverter
#(3). Using a custom converter
@app.route('/user/<phone:user_id>')
def user_info(user_id):
return user_id
1.3 Query parameter acquisition
#args: Query parameters
#(1). Query parameters
Query parameters in the URL China and Israel ? Separated from the main route, the query parameters appear in the form of key-value pairs, and the key and value use "=" Connection, as shown below :/user/?userid=333
#(2). Obtaining query parameters
request.args.get('key')
request.args['key']
#(3). Example :
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/')
def user_info():
# Pass ['key'] Object in the query parameters user_id
user_id_1 = request.args['userid']
# Pass get Method in the query to get the user_id
user_id_2 = request.args.get('userid')
return 'user_id_1:{},user_id_2:{}'.format(user_id_1,user_id_2)
# Access route : http://127.0.0.1:5000/?userid=333, You can see the results on the page
1.4 Form Data Acquisition
# form: Form data
#(1). Form data
form Form data, 1 Generally applied to login, registration, information submission and so on . Mating front end form Form uses,
1 Like form The forms are all post Request, pay attention to the specified in the route POST Request method, which encapsulates the form data in the request body
#(2). Form data acquisition mode
request.form.get('key')
#(3). Example
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/',methods=['post])
def login():
# Get form User name in form
username = request.form.get('uname')
# Get form Password in the form
password = request.form.get('pwd')
# Judgment of user name and password
if username == 'admin' and password == 'admin123':
return ' Login Successful '
else:
return ' Login failed '
if __name__ == '__main__':
app.run()
# postman Visit http://127.0.0.1:5000/, And specifies form-data For {'uname': 'admin', 'pwd': 'admin123'}
1.5 File Upload
# files: File data
# (1). Acquisition of file objects
file_obj = request.files.get('key')
# (2). Properties of file objects
file_obj.filename: File name of uploaded file
file_obj.name: Upload the file specified key
file_obj.save('path'): Saving method of file object
# Example :
from flask import Flask
from flask import request
# Create Flask Instance object
app = Flask(__name__)
@app.route('/upload', methods=['POST'])
def upload_file():
# Get the file object passed by the front end
img = request.files.get('pic')
# Gets the file name of the file object
file_name = img.filename
# Save a file object
img.save(file_name)
return ' Upload succeeded !'
if __name__ == '__main__':
app.run()
1.6 Additional request parameters
# Other parameters :
- headers: Record the message header in the request header
- method: Object used by the record request HTTP Request method
- url: Object that records the request URL Address
# Example :
from flask import Flask
from flask import request
# Create Flask Instance object
app = Flask(__name__)
@app.route('/')
def index():
# Print request header information
print(request.headers)
print('-'*50)
# Print request method
print(request.method)
print('-'*50)
# To print the requested URL
print(request.url)
return 'other args'
if __name__ == '__main__':
app.run()
2. Set of 3 new books responding to data
2.1 String response form
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
0
2.2 Template response format
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
1
Expand some jinjia2 template engines:
Jinjia2 template and our django built-in template syntax basic 1, we simply understand
We define the variable data in the view
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
2
Use defined variable data in templates
{{variable name}} displays the value of the variable
{% for statement%} Loop body {% endfor%}
<body>
<h1>{{ news.title }}</h1>
<h1> "Meritorious service - Li Yannian </h1>
{% for item in news.news_list %}
<p>{{ item }}</p>
{% endfor %}
</body>
2.3 Redirect response form
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
4
3. Response to json data and tuple data
3.1 json data response
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
5
3.2 Tuple data response
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
6
4. make_response () Custom Response
# Executive summary
1. Fixed parameter
2. Acquisition of fixed parameters
3. Converter
4. Custom converter
7
Summarize
This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!