requests.post () process parameter data packet and the difference parameter json

dict in python json format to be converted to the type of data need to use json library:

import json

<json> = json.dumps(<dict>)
<dict> = json.loads(<json>)

Note that python and json type this statement does not, by json.dumps () dictionary object conversion, end up with a string object, that is, the data in python json format is actually a character string

>>> j = json.dumps(<dict>)
>>> type(j)
<class 'str'>

Example:

#字典转换成json格式数据,得到字符串对象(unicode),与str类型有区别

dict = {"a":1,"b":"测试"}
print(type(dict))
to_json = json.dumps(dict,ensure_ascii=False)
print(to_json)

result:

<class 'dict'>
{"a": 1, "b": "测试"}

Although json data format of character string type is present in python, but the results str (), a function of the results obtained with the plant json.dumps () method is not the same as obtained

>>> d = {'a': 1, 'b': 2}
>>> d_d = {"a": 1, "b": 2}
>>> string = str(d)
>>> string_d = str(d_d)
>>> js = json.dumps(d)
>>> js_d = json.dumps(d_d)
>>> string == string_d
True
>>> js = js_d
True
>>> string == js
False
>>> string
"{'a': 1, 'b': 2}"
>>> js
'{"a": 1, "b": 2}'

Can be seen that the difference between string and js quotes. For string as json.loads () parameter object, in addition to the type of format to meet the dictionary, all the string objects must be double quotes.
It can be concluded that the format string js: single quotes, and python string type data: double quotes.

**

requests.post()

**
When POST request performed requests.post (), the incoming message has two parameters, one is the Data, is a json.
Common form Forms can be used as parameters for packet data submitted and data object is in python dictionary type;
encountered a payload packets during the latest reptile, the message is a json format, Therefore, incoming packets object should be formatted; there are two ways to submit messages:

import requests
import json

url = "http://example.com"
data = {
    'a': 1,
    'b': 2,
}
# 1-data参数需要使用json.dumps将字典类型的对象转换成json格式的字符串对象
r1 = requests.post(url, data=json.dumps(data))

# 2-json参数会自动将字典类型的对象转换为json格式
r2 = requests.post(url, json=data)
print(type(data))
print(r1)
print(r2)
<class 'dict'>
<Response [200]>
<Response [200]>

other

Params parameters may be used in requests.get () method to construct url
before requesting obtained results may sometimes garbled state, view Web pages through resp.encoding encoding properties, while the acquisition of resp.encoding resp.text = 'utf-8' assignment, this will again acquired resp.text we require the use of coding.

Reference: https: //www.cnblogs.com/yanlin-10/p/9820694.html
Reference: https: //www.jianshu.com/p/9095a27b1bf2

Published 82 original articles · won praise 43 · views 180 000 +

Guess you like

Origin blog.csdn.net/liudinglong1989/article/details/100714979