Python優雅的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不應該是這樣,當我們試圖讓http庫更加優雅的時候,我們找到了Requests,有一種相見恨晚的感覺。
今天推薦Requests給各位測試人也是有原因的,我們在工作中難免會碰到一些奇葩的性能測試需求,例如測試某個中間件的消息處理效率等,當然,如果你熟悉JAVA,他應該也是有一個類似的庫的。那么如果你是一個Pythoner,Requests無疑是你的第一選擇,我們來看一下它優雅的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/... |
一個自定義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估計已經按捺不住激動的心情。
在這里,你可以欣賞到更多API和EG。