Python哲學(xué):
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
一些高級(jí)用法:
- 多用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'})
# 參數(shù)會(huì)被合并
# 如果你想在一個(gè)session中刪除一個(gè)參數(shù),那么你只需要設(shè)置它為none,他便自動(dòng)被刪去。
- 常用的查看
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')
# 響應(yīng)的頭部信息
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'}
# 請(qǐng)求的頭部信息
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 # 非文本類(lèi)型,以二進(jìn)制形式
.....
print r.json # json格式
....
print r.encoding
'UTF-8'
- SSL 校驗(yàn)
requests.get('https://kennethreitz.com', verify=True)
# 指定 證書(shū)
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)
- 分塊編碼請(qǐng)求
'''
還請(qǐng)支持分塊傳輸編碼傳出和傳入的請(qǐng)求。
要發(fā)送一個(gè)數(shù)據(jù)塊編碼的請(qǐng)求,
只是提供一個(gè)生成器(或任何沒(méi)有長(zhǎng)度的迭代器)為您的BODY:
'''
def gen():
yield 'hi'
yield 'there'
requests.post('http://some.url/chunked', data=gen())
- 事件鉤子
我理解的就是發(fā)送HTTP請(qǐng)求,用回調(diào)來(lái)異步處理(鉤子就是回調(diào)的函數(shù))
r = requests.get('http://en.wikipedia.org/wiki/Monty_Python',
hooks=dict(response=print_url))
def print_url(r, *args, **kwargs):
print(r.url)
你可以通過(guò)傳遞一個(gè) { hook_name: callback_function} 字典給 hooks請(qǐng)求參數(shù),為每個(gè)請(qǐng)求分配一個(gè)鉤子函數(shù)。
callback_function會(huì)接受一個(gè)數(shù)據(jù)塊作為它的第一個(gè)參數(shù)。print_url 函數(shù)就會(huì)以response作為第一個(gè)參數(shù)。
若回調(diào)函數(shù)返回一個(gè)值,默認(rèn)以該值替換傳進(jìn)來(lái)的數(shù)據(jù)(response)。若函數(shù)未返回任何東西, 也沒(méi)有什么其他的影響。