Advanced Python library application interface testing --Requests

cookie settings

Cookie settings

import requests

cookie = {'hero': 'alix'}

r_cookie = requests.get(base_url + '/cookies', cookies= cookie)

print(r_cookie.text)

operation result

{
  "cookies": {
    "hero": "alix"
  }
}

 

Get cookie

Request Baidu home page, and then get cookie, to achieve the following:

r = requests.get('http://www.baidu.com')

print(type(r.cookies))

print(r.cookies)
for key,value in r.cookies.items():
    print(key + ":" + value)

Call cookies properties can successfully receive cookies, you can find it to be a RequestCookieJar type, then use items () commit method to convert it into two tables Ganso consisting of table output a Cookie of each name and value, to achieve Cookies traversal resolution.

 

time out

You can make requests after a timeout parameter set to describe the time to stop waiting for a response. Request does not prevent some consistent response waiting state.
The following case deliberately set a small time-out, to look at the response to treatment after a timeout.

cookie = {'hero': 'ariliya'}

r_timeout = requests.get(base_url + '/cookies', cookies=cookie, timeout=0.001)

print(r_timeout.text)

Timeout exception

requests.exceptions.ConnectTimeout: HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /cookies (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000017E45DFC860>, 'Connection to httpbin.org timed out. (connect timeout=0.001)'))

 

 

File Upload

Requests can be submitted using the parameter files analog data files, included some interface requires us to upload a file, we can also use it to upload, implementation is very simple examples are as follows:

file = {'file': open('01.jpg', 'rb')}

r_up = requests.post(base_url + '/post', files=file)

print(r_up.text)

Tips: To upload a file in the same directory

 

Session object

In the computer, especially in network applications, known as "session control." Session object required to store user-specific configuration information and attribute painting i. Thus, when the user to jump between the web page in the application, variables stored in the Session object will not be lost twenty unanimously exist throughout the user session.
For example, you first login operation carried out after the man opened the personal details page center, the center of the personal details page know how to show that just landed in the user's information, here you need to use Session to store information.
In the interface testing process is often dependent on the relationship between the interface, such as the following two requests defined format to another while getting cookie cookie, save the session in the absence of a few recruits, the second interface can not get the first set of interfaces cookie value

# Set cookie 
R & lt requests.get = (the base_url + ' / Cookies / SET / Hero / leesin ' ) 

Print (r.text) 


# acquires cookie, this cookie is empty, the need to save the acquired session cookie 

R01 = requests.get (the base_url + ' / Cookies ' ) 

Print (r01.text)

return value

{
  "cookies": {
    "hero": "leesin"
  }
}

{
  "cookies": {}
}

 

Requests session objects so you can cross the request to keep certain parameters. He also between all requests for the same session instance issues remain cookie.

# Generated session object 
S = requests.session () 

# Set Cookie 
R & lt s.get = (the base_url + ' / Cookies / SET / Hero / leesin ' ) 

Print (r.text) 

# Get Cookie 
R01 = s.get (the base_url + ' / Cookies ' ) 

Print (r01.text)

 

return value

{
  "cookies": {
    "hero": "leesin"
  }
}

{
  "cookies": {
    "hero": "leesin"
  }
}

Therefore, the use of simulation session can be done with a session, but not a single line of cookies problem, then the next step of the operation after the successful landing commonly used to simulate

 

Proxy Settings

Proxy (Proxy), also known as Network Agent, is a special kind of network service that allows a network outage (typically clients) via this service with another network indirect connection is interrupted (usually servers)
proxy server at the customer between the terminal and access the Internet, the server receives a client request, and then replace the ip address of the client makes a request to the target site, all traffic routes are from the proxy server in order to gain some resources are not directly available.
For some interfaces, at the time the test request several times, can get the content properly. But once you start a large-scale frequently requested (such as performance is) server might open verification; even ip ban. In order to prevent this from happening you need a proxy to solve this problem, we need to channel this parameter Requests proxies, the reptile the frequently used agents.

West thorn free agent

Proxy Settings

proxie = {'http': 'http://114.230.69.81:9999'}

r = requests.get(base_url + '/get', proxies=proxie)

print(r.text)

 

Authentication

Many interface requires authentication, Request supports multiple authentication
with the following types of cases verified two kinds of provinces: BasicAuth and DigestAuth

from requests.auth import HTTPBasicAuth
from requests.auth import HTTPDigestAuth

#BasicAuth

r_basic = requests.get(base_url + '/basic-auth/hero/leesin', auth= HTTPBasicAuth('hero', 'leesin'))

print(r_basic.text)

#DigestAuth

r_digest = requests.get(base_url + '/digest-auth/auth/hero/leesin', auth= HTTPDigestAuth('hero', 'leesin'))

print(r_digest.text)

return value

{
  "authenticated": true, 
  "user": "hero"
}

{
  "authenticated": true, 
  "user": "hero"
}

 

Streaming Request

There are a number of interfaces return value is rather special, not the word returns a result, more than twenty results, for example, a query interface that returns a value of merchandise before 10 ranking information.
Practice cases
request interface as follows:
http://httpbing.org/stream/{num}
return a result set num is the number, such as 10 10 different input id result returned
our process the result set for this type of interface iter_lines need to use an iterative approach to office in ():

Import JSON 
R & lt = requests.get (the base_url + ' / Stream / 10 ' , Stream = True)
 # Print (r.encoding) 

# If the response content is not set encoding, the default setting. 8-UTF 
IF r.encoding IS None: 
    r.encoding = ' UTF-. 8 ' 

# response iterative processing results 
for Line in r.iter_lines (decode_unicode = True):
     IF Line: 
        Data = json.loads (Line)
         Print (Data [ ' ID ' ])

return value

0
1
2
3
4
5
6
7
8
9

 

Guess you like

Origin www.cnblogs.com/youngleesin/p/11109270.html