Python优雅的Requests库助力性能测试

发表于:2014-1-14 11:38

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:小A    来源:51Testing软件测试网采编

  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。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号