Use the methods and properties of Flask.Request to get get and post request parameters (2)

1. Request in Flask

When Python sends Post, Get and other requests, we use the requests library. There is a request library in Flask, which has some unique methods and attributes. Note that it is not the same as requests.

2. Post request: request.get_data()

It is used by the server to obtain the data requested by the client. Note: It is raw data without any processing regardless of the content type. If the data is in json, it will be obtained as a json string, and the sorting is consistent with the request parameters.

2.1 Flask code

Examples of different methods only need to replace the view function, and only the view function will be shown later.

# 注意:flask中的request和requests库不是同一个,要区分开
from flask import Flask, request

# 创建一个flask实例
app = Flask(__name__)


# 视图函数,只允许get和post请求
@app.route('/', methods=['GET', 'POST'])
def request_flask():
    # 获取未经处理过的原始数据而不管内容类型,如果数据格式是json的
    # 则取得是json字符串,排序和请求参数一致
    data = request.get_data()
    print(data)
    print(type(data))
    return 'hello world'


if __name__ == '__main__':
    app.run()

2.2 Test code (applied to subsequent chapters, no more details)

import requests

data = {
    
    
    "username": "cc",
    "password": "123456"
}

url = "http://127.0.0.1:5000/"
resp = requests.post(url=url, json=data)
print('post:', resp)
print('post:', resp.text)

resp = requests.get(url=url, params=data)
print('get:', resp)
print('get:', resp.text)

2.3 Implementation effect

2.3.1 Flask

The request data obtained by get.data() is a byte stream, and the ordering is consistent with the request parameters.
insert image description here

2.3.2 Request result

Both get and post requests succeed.
insert image description here

3. Post request: request.data

The obtained raw data is also unprocessed. If the data format is json, the obtained is a json string, and the sorting is consistent with the request parameters. request.get_data() has the same effect

4. Post request: request.get_json()

The request parameters are processed to obtain a dictionary format, so the sorting will be disrupted, according to the dictionary sorting rules .

4.1 Flask code

# 视图函数,只允许get和post请求
@app.route('/', methods=['GET', 'POST'])
def request_flask():
	  # 将请求参数做了处理,得到字典格式,因此排序会打乱,依据字典排序规则。
    data = request.get_json()
    print(data)
    print(type(data))
    # 服务端就可以根据字典进行取值
    username = request.get_json()["username"]
    print(username)
    return 'hello world'

4.2 Implementation effect

4.2.1 Flask

The request parameters are processed to obtain a dictionary format, which is convenient for the server to obtain values ​​by pressing keys , and the extracted username is "cc".

Note: the get request does not have a dictionary and cannot take values, and the get method can be commented out at runtime.
insert image description here

4.2.2 Request result

The post request is successful.
insert image description here

5. Post request: request.json

Same effect as request.get_json(). The result is in dictionary format, so the sorting will be messed up, according to the dictionary sorting rules.

code show as below:

# 视图函数,只允许get和post请求
@app.route('/', methods=['GET', 'POST'])
def request_flask():
	# 将请求参数做了处理,得到的是字典格式的,因此排序会打乱,依据字典排序规则
    data = request.json
    print(data)
    print(type(data))
    # 如果这里的key服务端写错了,客户端请求时,就会出现500
    username = request.json['username']
    print(username)
    return 'hello world'

6. Get request: request.args.get()

6.1 Flask code

# 视图函数,只允许get和post请求
@app.route('/', methods=['GET', 'POST'])
def request_flask():
	# 可以获取单个的值
    username = request.args.get("username")
    print(username)

    return 'hello world'

6.2 Execution Results

The server got the username value "cc"
insert image description here

7. Get request: request.args.to_dict()

7.1 Flask code

# 视图函数,只允许get和post请求
@app.route('/', methods=['GET', 'POST'])
def request_flask():
	# 可以获取get请求的所有参数,返回值是ImmutableMutiDict(不可变的多字典)类型
    i = request.args
    print(i)
    # 将获得的参数转化成字典
    j =  i.to_dict()
    print(j)
    print(type(j))
    print(j["username"])
    return 'hello world'

7.2 Execution Results

insert image description here

8. Simulate request error reporting

8.1 500 Internal Server Error

When the server key is wrongly written, a 500 error will be reported. For example, you can change the key username to usename, and see the effect after running.
insert image description hereinsert image description here

8.2 404 Not Found

Only the instance is created, and there is no view function. After starting the socket service, the access address will report 404. Or the request url is filled incorrectly.

from flask import Flask

# 创建一个flask实例
app = Flask(__name__)

if __name__ == '__main__':
    app.run()

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_44691253/article/details/132185497