1. 程式人生 > >使用Python的Requests庫進行web接口測試

使用Python的Requests庫進行web接口測試

異常 part instead range 導入 2.7 text 部分 pub

1、Requests簡介
Requests 是使用 Apache2 Licensed 許可證的 HTTP 庫。用 Python 編寫,真正的為人類著想。

Python 標準庫中的 urllib2 模塊提供了你所需要的大多數 HTTP 功能,但是它的 API 太渣了。它是為另一個時代、另一個互聯網所創建的。它需要巨量的工作,甚至包括各種方法覆蓋,來完成最簡單的任務。

總之,大家以後對urllib2庫敬而遠之就行了。來擁抱Requests吧。

Requests的官方文檔:http://cn.python-requests.org/zh_CN/latest/

通過下面方法安裝requests

pip install requests

2、Requests如何發送HTTP請求
非常簡單,先導入requests,

import requests
然後,按照下面的方法發送http的各種請求:
r = requests.get(‘https://github.com/timeline.json‘)
r = requests.post("http://httpbin.org/post")
r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")

3、為URL傳遞參數
如果http請求需要帶URL參數(註意是URL參數不是body參數),那麽需要將參數附帶到payload字典裏頭,按照下面的方法發送請求:

import requests
payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
r = requests.get("http://httpbin.org/get",params=payload)
print r.url
通過print(r.url)能看到URL已被正確編碼:
http://httpbin.org/get?key2=value2&key1=value1
註意字典裏值為 None 的鍵都不會被添加到 URL 的查詢字符串裏。

4、unicode響應內容
import requests
r = requests.get(‘https://github.com/timeline.json‘)
r.text
響應結果是:
{"message":"Hello there, wayfaring stranger. If you‘re reading this then you probably didn‘t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}
Requests會自動解碼來自服務器的內容。大多數unicode字符集都能被無縫地解碼。請求發出後,Requests會基於HTTP頭部對響應的編碼作出有根據的推測。當你訪問r.text之時,Requests會使用其推測的文本編碼。你可以找出Requests使用了什麽編碼,並且能夠使用r.encoding 屬性來改變它

>>> r.encoding
‘utf-8‘
5、二進制響應內容
如果請求返回的是二進制的圖片,你可以使用r.content訪問請求響應體。

import requests
from PIL import Image
from StringIO import StringIO
r = requests.get(‘http://cn.python-requests.org/zh_CN/latest/_static/requests-sidebar.png‘)
i = Image.open(StringIO(r.content))
i.show()
6、JSON響應內容
Requests中也有一個內置的JSON解碼器,助你處理JSON數據:

import requests
r = requests.get(‘https://github.com/timeline.json‘)
print r.json()
r.json將返回的json格式字符串解碼成python字典。r.text返回的utf-8的文本。
7、定制請求頭
如果你想為請求添加HTTP頭部,只要簡單地傳遞一個 dict 給headers 參數就可以了。

import requests
import json
payload = {‘some‘: ‘data‘}
headers = {‘content-type‘: ‘application/json‘}
r = requests.get(‘https://github.com/timeline.json‘, data=json.dumps(payload), headers=headers)
print r.json()
註意,這裏的payload是放到body裏面的,所以params參數要使用json數據。
8、POST請求
就像上面‘定制請求頭’中的例子,將payload序列化為json格式數據,傳遞給data參數。

9、POST提交文件
先制作一個text文件,名為‘report.txt’,內容是‘this is a file’。Requests使得上傳多部分編碼文件變得很簡單:

import requests

url = ‘http://httpbin.org/post‘
files = {‘file‘: open(‘report.txt‘, ‘rb‘)}
r = requests.post(url, files=files)
print r.text
返回結果是:
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py
{
"args": {},
"data": "",
"files": {
<strong>"file": "this is a file"</strong>
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "160",
"Content-Type": "multipart/form-data; boundary=a3b41a6300214ffdb55ddbc23dfc0d91",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.7.0 CPython/2.7.9 Windows/2012Server"
},
"json": null,
"origin": "202.108.92.226",
"url": "http://httpbin.org/post"
}


Process finished with exit code 0
10、POST提交表單
傳遞一個字典給 data 參數就可以了。數據字典在發出請求時會自動編碼為表單形式:

>>> payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘}
>>> r = requests.post("http://httpbin.org/post", data=payload)
查看響應內容:
>>> print r.text
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.6.0 CPython/2.7.10 Windows/7"
},
"json": null,
"origin": "124.251.251.2",
"url": "http://httpbin.org/post"
}

11、響應狀態碼
使用r.status_code返回響應的狀態碼。

import requests

r = requests.get(‘http://httpbin.org/get‘)
print r.status_code
為方便引用,Requests還附帶了一個內置的狀態碼查詢對象:
print r.status_code == requests.codes.ok
12、失敗請求拋出異常
如果發送了一個失敗請求(非200響應),我們可以通過 Response.raise_for_status()來拋出異常:

import requests

bad_r = requests.get(‘http://httpbin.org/status/404‘)
print bad_r.status_code
bad_r.raise_for_status()
返回結果是:
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py
404
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py", line 5, in <module>
bad_r.raise_for_status()
File "C:\Python27\lib\site-packages\requests\models.py", line 851, in raise_for_status
raise HTTPError(http_error_msg, response=self)
<strong>requests.exceptions.HTTPError: 404 Client Error: NOT FOUND</strong>

Process finished with exit code 1
如果返回碼是200,則不會拋出異常,即:
import requests

bad_r = requests.get(‘http://httpbin.org/get‘)
print bad_r.status_code
bad_r.raise_for_status()
的返回結果是:
C:\Python27\python.exe C:/Users/Administrator/PycharmProjects/flaskexample/postfile.py
200

Process finished with exit code 0
13、響應頭
我們可以查看以一個Python字典形式展示的服務器響應頭:

讀取全部頭部:

r.headers
返回:
{
‘content-encoding‘: ‘gzip‘,
‘transfer-encoding‘: ‘chunked‘,
‘connection‘: ‘close‘,
‘server‘: ‘nginx/1.0.4‘,
‘x-runtime‘: ‘148ms‘,
‘etag‘: ‘"e1ca502697e5c9317743dc078f67693f"‘,
‘content-type‘: ‘application/json‘
}
讀取某一個頭部字段:
r.headers[‘Content-Type‘]
r.headers.get(‘content-type‘)
14、Cookies
得到響應中包含的一些Cookie:

>>> url = ‘http://example.com/some/cookie/setting/url‘
>>> r = requests.get(url)

>>> r.cookies[‘example_cookie_name‘]
‘example_cookie_value‘
要想發送你的cookies到服務器,可以使用 cookies 參數:
>>> url = ‘http://httpbin.org/cookies‘
>>> cookies = dict(cookies_are=‘working‘)

>>> r = requests.get(url, cookies=cookies)
>>> r.text
返回結果:
u‘{\n "cookies": {\n "cookies_are": "working"\n }\n}\n‘

15、重定向與請求歷史
默認情況下,除了 HEAD, Requests會自動處理所有重定向。

可以使用響應對象的 history 方法來追蹤重定向。

>>> r = requests.get(‘http://github.com‘)
>>> r.url
‘https://github.com/‘
>>> r.status_code
200
>>> r.history
[<Response [301]>]
如果你使用的是GET, OPTIONS, POST, PUT, PATCH 或者 DELETE,,那麽你可以通過 allow_redirects 參數禁用重定向處理:
>>> r = requests.get(‘http://github.com‘, allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
如果你使用的是HEAD,你也可以啟用重定向:
>>> r = requests.head(‘http://github.com‘, allow_redirects=True)
>>> r.url
‘https://github.com/‘
>>> r.history
[<Response [301]>]



使用Python的Requests庫進行web接口測試