Python優(yōu)雅的Requests庫助力性能測試
Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.
Things shouldn’t be this way. Not in Python.
是的,Python的urllib2不應(yīng)該是這樣,當(dāng)我們試圖讓http庫更加優(yōu)雅的時(shí)候,我們找到了Requests,有一種相見恨晚的感覺。
今天推薦Requests給各位測試人也是有原因的,我們在工作中難免會(huì)碰到一些奇葩的性能測試需求,例如測試某個(gè)中間件的消息處理效率等,當(dāng)然,如果你熟悉JAVA,他應(yīng)該也是有一個(gè)類似的庫的。那么如果你是一個(gè)Pythoner,Requests無疑是你的第一選擇,我們來看一下它優(yōu)雅的DEMO:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass')) >>> r.status_code 200 >>> r.headers['content-type'] 'application/json; charset=utf8' >>> r.encoding 'utf-8' >>> r.text u'{"type":"User"...' >>> r.json() {u'private_gists': 419, u'total_private_repos': 77, ...} |
Requests提供了最簡便的JSON解析方法,類似于這樣:
>>> import requests >>> r = requests.get('https://github.com/timeline.json') >>> r.json() [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/... |
一個(gè)自定義header的例子,POST
>>> import json >>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> headers = {'content-type': 'application/json'} >>> r = requests.post(url, data=json.dumps(payload), headers=headers) |
看到這里,各位Pythoner估計(jì)已經(jīng)按捺不住激動(dòng)的心情。
在這里,你可以欣賞到更多API和EG。