Summary of the use of requests in interface testing

The main
reason is to see the value in the response object res: 1) .encoding: res.encoding in the response 2) .status_code in the response: res.status_code 3) .text in the response: res.text (in string format ) 4) .json() in the response: res.json() (in dictionary format) 5).headers: res.headers in the response 6).cookies: res.cookies in the response 7).content in the response : res.content (Get response information in bytecode, including multimedia formats such as pictures and videos)
1. Get (query) request with parameters: paramas is a dictionary format or string (dictionary is recommended)
1) Request address: http: //xxx.com?id=1
parameter params = {"id": 1}, then res = requests.get(url, paramas=params)
2) Request address: http://xxx.com?id=1, 2 The
parameter is params = {"id": "1,2"}, then res = requests.get(url, paramas=params) (but note: commas will be converted into ASCI value 2C)
3) Request address: http ://xxx.com?id=1&app=test
parameter is params = {"id": 1, "app": "test"}, then res = requests.get(url, paramas=params)
2. post (new Add) Request:
1) The parameter params is in json format: a string in json format
The request header is headers={"Content-Type":"json"}
res = requests.post(url, json=data, headers=headers)
or
res = requests.post(url, data=json.dumps(data), headers=headers) # Convert the dictionary object into a json string json.dumps(data)
2) The parameter params is data format: it is a dictionary object. The
request header is headers={"Content-Type":"application/x-www-form -urlencoded”}
res = requests.post(url, data=data,headers= headers)
3. Put request (modification):
request address: http://xxx.com/id=1/ (Note: id must be specified )
res = requests.put(url, json=data,headers= headers)
4. Delete request (delete):
Request address: http://xxx.com/id=1/ (Note: 1) No headers are required 2) Generally, there is no response text, only the response status is 204)
res = requests.delete(url)
5. res.encoding: 1) View the default encoding 2) Set the response encoding format res.encoding = "utf-8" (for (I want to use Chinese in the text)
6, res.headers: usually used to extract the token/session returned by the server
from urllib import parse # Introduce splicing url function
url = parse.urljoin(HOST, excUrl)
7. res.cookies: usually used to extract cookies (returned is a dictionary object)
from requests.cookies import RequestsCookieJar # Introduce cookies package
cookies = res .cookies.RequestsCookieJar() # define a cookies object
cookies.update(res.cookies) # update the obtained cookies
8. res.content: get the picture information (the url must have img and other formats)
write the obtained picture
Go to a directory and use binary format with open(".../report/test.png", "wb") as f:
f.write(res.content)

Guess you like

Origin blog.csdn.net/qq_37405087/article/details/109997439