3. Different types of parameters for requests

In the previous article, we introduced several kinds of request types with parameters. This article, through the API on github, to demonstrate one by one parameter interface.
1. Get request without parameters

# 导入requests包
import requests 

# 1. 组装请求
url = "https://api.github.com"  # 这里只有url,字符串格式
# 2. 发送请求,获取响应
res = requests.get(url) # res即返回的响应对象
# 3. 解析响应
print(res.json)  # 输出响应的文本

The res.json() method actually uses json.loads(res.text) to try to convert the response text into a dictionary in JSON format. Due to the abnormality of this method (for example, it returns JSON format under normal circumstances, and returns non-JSON format error information when 500 error is reported), it is recommended to use try...except to deal with, modify as follows.

import requests
url = 'https://api.github.com'
url_params = {
    
    'name': '浩浩', 'age': '18'}
res = requests.get(url, params=url_params)
try:
    print('响应文本转为字典', res.json())
except:
    print('响应文本', res.text)

2. Get request with parameters

import requests 

url = "https://api.github.com/openapi/api?key=ec961279f453459b9248f0aeb6600bbe&info=你好"  # 参数可以写到url里
res = requests.get(url=url) # 第一个url指get方法的参数,第二个url指上一行我们定义的接口地址
print(res.text)  

URL only supports ASCII (American Standard Code). In the actual transmission process, Chinese and some special characters need to go through urlencode (URL encoding). The interface address in the above example will be encoded as:
https://api.github.com/get?name=%E4%B8%B4%E6%B8%8A&age=18

Or write like this`

import requests 

url = "https://api.github.com/openapi/api"
params = {
    
    "key":"ec961279f453459b9248f0aeb6600bbe","info":"你好"} # 字典格式,单独提出来,方便参数的添加修改等操作
res = requests.get(url=url, params=params) 
print(res.text)  

It should be noted that in the requests.get() method, the parameter params is followed by a dictionary, and requests will automatically splice this parameter into the interface request address for us.
3. Traditional form POST request (x-www-form-urlencoded )

import requests 

url = "https://api.github.com"
data = {
    
    "name": "浩浩", "age": 18} # Post请求发送的数据,字典格式
res = requests.post(url=url, data=data) # 这里使用post方法,参数和get方法一样
print(res.text)  

4. POST request of JSON type (application/json)

import requests 

url = "https://api.github.com"
data = '''{
        "name": "浩浩",
        "age": 18
        }''' # 多行文本, 字符串格式,也可以单行(注意外层有引号,为字符串) data = '{"name": "浩浩", "age": 18}'
res = requests.post(url=url, data=data) #  data支持字典或字符串
print(res.text)  

The data parameter supports dictionary format and string format. If it is a dictionary format, the requests method will convert it into a string according to the default form urlencoded format. If it is a string, it will not be converted.
If data is transmitted in string format, the following points need to be followed :

It must be a strict JSON format string, double quotes must be used inside, there must be a comma between kv, and the boolean value must be lowercase true/false, etc.
There cannot be Chinese, and the direct string will not be automatically encoded.
Generally speaking, it is recommended Declare data as a dictionary format (to facilitate data addition and modification), and then use the json.dumps() method to convert the data into a legal JSON string format

import requests 
import json # 使用到JSON中的方法,需要提前导入

url = "https://api.github.com"
data = {
    
    
        "name": "浩浩",
        "age": 18
        }  # 字典格式,方便添加
headers = {
    
    "Content-Type":"application/json"} # 严格来说,我们需要在请求头里声明我们发送的格式
res = requests.post(url=url, data=json.dumps(data), headers=headers) #  将字典格式的data变量转换为合法的JSON字符串传给post的data参数
print(res.text)  

Or directly assign the data data in the dictionary format to the JSON parameter of the post method (the dictionary format will be automatically converted into legal JSON text and headers will be added)

import requests 

url = "https://api.github.com/openapi/api/v2"
data = {
    
    
	"reqType":0,
    "perception": {
    
    
        "inputText": {
    
    
            "text": "哈哈哈"
        },
        "inputImage": {
    
    
            "url": "imageUrl"
        },
        "selfInfo": {
    
    
            "location": {
    
    
                "city": "北京",
                "province": "北京",
                "street": "古城南街"
            }
        }
    },
    "userInfo": {
    
    
        "apiKey": "ec961279f453459b9248f0aeb6600bbe",
        "userId": "206379"
    }
} 
res = requests.post(url=url, json=data) # JSON格式的请求,将数据赋给json参数
print(res.text)  

5. Sending data
in XML format. The above example mentioned that both XML and JSON are data in Raw format. XML and JSON are actually text strings in different formats in Python. We can send the string to the data parameter of the request method as it is, that is, the data parameter has the following three functions:

1) data = {} or [(,), (,)]: Accepts data in a dictionary or nested list format, which will be encoded according to the form Url
2) data ='': Accepts a string or bytes binary string , It will be sent as-is (need to manually add the request header, if there is Chinese, it needs to be manually encoded)
3) data = open('...','rb'): accept a file object and upload it in binary format.
To send data in XML format, just pass a multi-line string in XML format to the data parameter of the request method. An example is as follows.

import requests
url = 'https://api.github.com/post'
xml_data = '''
<xml>
    <name>浩浩</name>
    <age>18</name>
</xml>
'''
headers = {
    
    'Content-Type': 'application/xml'}

res = requests.post(url, data=xml_data.encode('utf-8'), headers=headers)
print(res.text)

Because there is a non-ASCII code in the xml_data data, the data needs to be encoded as a bytes binary string in utf-8 format and sent. Since the request header is not automatically added when sending data in the Raw format, it is generally necessary to manually add the content type declaration in the request header, and pass the constructed dictionary type request header variable to the keyword parameter headers of the request method.
6. Send Multipart/form-data request (file upload)
There are two forms on the web page. One is that does not include file upload. All data entered or selected by the user can be expressed in string format. This is called a normal form. Or a plain text form, the corresponding MIME type is application/x-www-form-urlencoded.

The other includes ordinary input boxes, etc., but also contains one or more file upload boxes. The variable value in the ordinary input box can be encoded in a string format, while the uploaded file (such as a picture file) may not be directly converted to a string, and binary format should be used. Therefore, it is necessary to use a multipart mixed format, which I call a mixed form, and the corresponding MIME type is multipart/form-data. In the form, each file to be uploaded corresponds to a specified variable just like the ordinary input box. Therefore, you can also use the dictionary format to assemble the request data of the mixed form and pass it to the files parameter of the request method. The example is as follows.

import requests
url = 'https://api.github.com/post'
multi_form_data = {
    
    
    'name': '浩浩',
    'age': '18',  # 不能使用int类型
    'avatar': open('/Users/apple/Pictures/robot.png', 'rb'),
    'avatar2': open('/Users/apple/Pictures/robot.jpg', 'rb'),
}

res = requests.post(url, files=multi_form_data)
print(res.text)

The numbers in the form data should be in string format, and the file should be opened and transmitted in rb binary format, supporting multiple variables and multiple files.

The data avatar of the file type can only pass through an open file object open('/Users/apple/Pictures/robot.png','rb'), or it can pass three parameters: the name of the file to be saved, the opened file and File MIME type, ie

‘avatar’: (‘robot.png’, open(’/Users/apple/Pictures/robot.png’, ‘rb’), ‘image/png’),

For example, some interfaces must declare the file name and MIME type when uploading Excel files, such as:

res = request.post(url, files={
    
    'upload_file': 
        ('data.xlsx', 
        open('data.xlsx', 'rb'),
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    })

7. Send Binary format data (single file/streaming upload)

import requests
url = 'https://api.github.com/post'

res = requests.post(url, data=open('/Users/apple/Pictures/robot.jpg', 'rb'))
print(res.text)

This is rare, just know it.

If you don’t understand, you can add vx: 18547673653 or qq: 1270059901

Guess you like

Origin blog.csdn.net/weixin_45608577/article/details/109635754