python requests库

Python哲学:

beautiful is better than ugly!

simple is better than complex!

complex is better than complicate

http://cn.python-requests.org/zh_CN/latest/user/advanced.html#event-hooks

一些高级用法:

  • 多用session
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print r.text
# '{"cookies": {"sessioncookie": "123456789"}}'

# 登陆
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'})
# 参数会被合并

# 如果你想在一个session中删除一个参数,那么你只需要设置它为none,他便自动被删去。
  • 常用的查看
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')

# 响应的头部信息
print  r.headers

{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}

# 请求的头部信息
print r.request.headers

{'Accept-Encoding': 'identity, deflate, compress, gzip',
'Accept': '*/*', 'User-Agent': 'python-requests/1.2.0'}


print r.text   #返回body,以文本的形式
....

print r.content # 非文本类型,以二进制形式
.....

print r.json # json格式
....

print r.encoding
'UTF-8'



  • SSL 校验
 requests.get('https://kennethreitz.com', verify=True)
 # 指定 证书
 requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

  • 流上传大文件
with open('massive-body') as f:
    requests.post('http://some.url/streamed', data=f)
  • 分块编码请求
'''
还请支持分块传输编码传出和传入的请求。
要发送一个数据块编码的请求,
只是提供一个生成器(或任何没有长度的迭代器)为您的BODY:
'''
 
def gen():
    yield 'hi'
    yield 'there'
 
requests.post('http://some.url/chunked', data=gen())
  • 事件钩子
    我理解的就是发送HTTP请求,用回调来异步处理(钩子就是回调的函数)
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python',
hooks=dict(response=print_url))

def print_url(r, *args, **kwargs): 
    print(r.url)

你可以通过传递一个 { hook_name: callback_function} 字典给 hooks请求参数,为每个请求分配一个钩子函数。
callback_function会接受一个数据块作为它的第一个参数。print_url 函数就会以response作为第一个参数。
若回调函数返回一个值,默认以该值替换传进来的数据(response)。若函数未返回任何东西, 也没有什么其他的影响。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容