Requests库学习

Requests的介绍:

最近在找代码看,在github上找到一个http的库,阅读了一部分api和源代码,此文记录下.

 

在python下,自带了urlib2的类似的库,但是作者觉得写的不好用,不够优雅,于是自己搞了个Requests出来.号称"HTTP FOR HUMAN",哈哈.


看基本的代码,的确要简洁很多.关于对比,在github上有一段有趣的讨论,可以看看.

https://gist.github.com/973705

话说,github是程序员的社区,可以多多关注.

 

文档重要内容记录:

 

文档链接:http://docs.python-requests.org/en/latest/

API:http://docs.python-requests.org/en/latest/api/

大部分看官方文档就可以了,写的很是清楚了.

例子中讲了get,post,options等操作.cookie,response的编码问题.

需要区分response.text和response.content的区别.

A session object has all the methods of the main Requests API.

Sessions can also be used to provide default data to the request methods. 

 

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
 

Any dictionaries that you pass to a request method will be merged with the session-level values that are set. The method-level parameters override session parameters.

Requests.request方法返回的response对象中包含了创建的request.


通过stream,可以在拿到头的时候,判断是否要继续下载response的body部分.


代理的运用:


使用hook,可以在请求返回时,调用相应的function,这个跟ajax的回调类似.目前支持的钩子仅仅为response(即响应返回时)


自定义认证方式:

Any callable which is passed as the auth argument to a request method will have the opportunity to modify the request before it is dispatched.



作者关于Requests的演讲稿:http://python-for-humans.heroku.com/#1


其他知识点:

在阅读代码过程中,了解如何安装包(用pip或者easy_install命令,会直接下载安装),以及setup.py的作用.

以及__init__.py的作用是:表明此目录应该被作为一个package来处理,对于import很多package很有用.

 

源代码解读:

源代码才看完sessions.py相关的代码.后面等全部看完了,再做个总结.

 

Requests中的关于认证部分:

httpBasicAuth(基本认证):http://zh.wikipedia.org/wiki/HTTP%E5%9F%BA%E6%9C%AC%E8%AE%A4%E8%AF%81

HttpDegistAuth(摘要认证):http://zh.wikipedia.org/wiki/HTTP%E6%91%98%E8%A6%81%E8%AE%A4%E8%AF%81


两者的区别是安全性上,前者是提供明文的用户名密码信息.后者使用随机数,MD5加密以及qop等来指定加密级别.在Requests的代码中可以看到是按照该规范来进行实现的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值