Python+requests implementing interface Tests-get and post requests used

Source: Internet
Author: User

Introduction: Requests is written in Python language, based on Urllib, using Apache2 Licensed Open Source Protocol HTTP library. It is more convenient than urllib, it can save us a lot of work, fully meet the requirements of HTTP testing. Requests's philosophy was developed in the center of the PEP 20 idiom, so it is more pythoner than Urllib. The more important thing is that it supports Python3 Oh!

First, installation

To have the PIP installed:

PIP Install requests

After installation, run a simple example to see if the installation was successful:

Import Requests                                 #导入requests包r =requests.get (url= ' https://www.baidu.com/')    print (R.status_code)                            # View the status of the request returned # results 200

  

Ii. several types of requests

①get Request: requests.get (' url ')

②post Request: Requests.post ("Url/post")

③put Request: Requests.put ("Url/put")

④delete Request: Requests.delete ("Url/delete")

⑤head Request: Requests.head ("Url/get")

⑥options Request: Requests.options ("Url/get")

Third, GET request

Passing URL parameters

In a GET request, it is allowed to use the params keyword to pass these parameters in a dictionary, for example:

content={' PageIndex ': 1, ' pageSize ': Ten, ' CategoryId ': 9}   r=requests.get (' http://www.xxxxx.com/api/v2/ Activities ', params=content) print (R.url)                       #获取请求内容print (r.text)                      #获取响应内容 # results http://www.xxxx.com/api/v2/ activities?pageindex=1&pagesize=10&categoryid=9{"Data": [], "PageIndex": 1, "Totalnum": 0, "Hasmore": false, " PageSize ": 0}

If a value of None exists in the dictionary, it is not added to the URL request.

content={' PageIndex ': 1, ' pageSize ': Ten, ' CategoryId ': None}   r=requests.get (' http://www.xxxxx.com/api/v2/ Activities ', params=content) print (R.url)                      #结果http://www.xxxx.com/api/v2/activities?pageindex=1&pagesize= 10

  

PS: If you do not use the params, you can also enter the entire address in the request, the same effect, such as:

R=requests.get (' http://m.xxxxx.com/api/v2/activities?pageIndex=1&pageSize=10&categoryId=9 ')

Note: in some get requests, you need to identify the user, so you will need to send the cookie content in the request, such as some pages that require users to log in to access, which will be explained in the next article.

Iv. Post Requests

1. Pass parameters as a form:

To send some form of data, simply pass a dictionary to the data keyword, which is automatically encoded as a form when the request is sent, for example:

content={' key1 ': ' value1 ', ' key2 ': ' value2 '}r=requests.post (' Http://www.xxx/api/v1/user/login ', data=content)

2. Pass the parameters in JSON form:

In many cases, the data you want to send is not a form, but a JSON-formatted string, if the content passed to the data keyword is not a dict, but

A string that, when sent, is sent directly to the data and is not automatically encoded as a form.

In order to convert a data structure into a JSON-formatted string, you first need to import a JSON package , two commonly used methods are:json.dumps () and json.loads ()

Import jsoncontent={' name ': ' Nee ', ' age ': '}str_content=json.dumps ' (content)      #把dick编码为json格式的字符串print (str_ Content) print (type (str_content)) #结果: {"name": "Nee", "Age": "+"}<class ' str ' >                        #此时的类型为strcontent = Json.loads (str_content)      #把json格式的字符串解码为原先的数据结构print (content) print (type content) #结果 {' name ': ' Nee ', ' age ': ' 18 '}<class ' dict ' >

Note: The basic types supported by 1.json encoding are: None, bool, int, float, string, list, tuple, Dict. For dictionaries, JSON assumes that key is a string (any non-string key in the dictionary is converted to a string at encoding), and to conform to the JSON specification, only Python lists and dictionaries should be encoded.                    In addition, it is a standard practice to define the topmost object as a dictionary in a Web application. The 2.json encoded format is almost identical to the Python syntax, slightly different: True will be mapped to true,false mapped to False,none will be mapped to null, and tuples () will be mapped to lists [], such as:

Content={' A ': None, ' B ': True, ' C ': False, ' d ':()}str_content=json.dumps (content) print (str_content) #结果: {"A": null, "B": True, "C": false, "D": [1, 2]}

therefore , to use the data keyword in a POST request to pass the character channeling in JSON format, you first haveto convert Dict to string, for example:

Import requestsimport jsonurl= ' Http://www.xxx.com/api/v1/user/login ' data={"ua": "13700002000", "PW": "12QWASZX", "ct ": 12}r=requests.post (data)         #在一些post请求中, also need to use the Headers section, which is not added here, in the following will be said to   print (r.text) # result {"NewUser": false, "user": {"userId": 531, "Mobileno": "13700002000", "UserName": "Test User 2000" ...}

In addition to being able to pass parameters as string after Dick encoding, they can be passed directly using the JSON keyword, which encodes itself as a string type when passed

Import requests            #不需要导入json模块url = ' http://xxxx/api/v1/user/login ' data={"ua": "13700002000", "PW": "12QWASZX", "ct ": 12}r=requests.post (Url,json=data)

The head section and the cookie part used in the POST request. This will be explained in a later article.

V. Response

1. Response status

After the request is sent successfully, you can use Status_code to view the status (the specific meaning of each status representative is not described in this article)

Import requestsr=requests.get (URL) print (r.status_code)-----Results-----200

2. Response Content

In the above content, it has been shown that the text is used to get the content, and the content returned is string

Import requestsr=requests.get (URL) print (r.text) print (Type (r.text))       #查看返回内容的类型-----Results-----..........                 #返回的具体内容 <class ' str ' >              

In addition, the requests also comes with a built-in JSON decoder that converts the returned content to Dict

Import requestsr.requests.get (URL) print (R.json ()) Print (Type (R.json ()))-----results-----...... <class ' dict ' >

It is convenient to look at the value of a specific parameter in the returned content after the JSON decoder is converted to Dict.

3. Response Content Encoding format

When getting response content, you can use r.encoding to view the encoding format of the content

Import requestsr=requests.get (URL) print (r.encoding)-----Results-----UTF-8

You can also specify the encoding, and when the encoding is changed, each time you get the response, you will use the new encoding method

Import requestsr=requests.get (URL) r.encoding= ' iso-8859-1 ' Print (r.text)

4. Response header Content

Import requestsr=requests.get (URL) print (r.headers)

5.cookies

Import requestsr=requests.get (URL) print (r.cookies)

  

Python+requests implementing interface Tests-get and post requests used

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.