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'})
# 參數(shù)會被合并

# 如果你想在一個session中刪除一個參數(shù),那么你只需要設置它為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)
  • 分塊編碼請求
'''
還請支持分塊傳輸編碼傳出和傳入的請求。
要發(fā)送一個數(shù)據(jù)塊編碼的請求,
只是提供一個生成器(或任何沒有長度的迭代器)為您的BODY:
'''
 
def gen():
    yield 'hi'
    yield 'there'
 
requests.post('http://some.url/chunked', data=gen())
  • 事件鉤子
    我理解的就是發(fā)送HTTP請求,用回調(diào)來異步處理(鉤子就是回調(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)

你可以通過傳遞一個 { hook_name: callback_function} 字典給 hooks請求參數(shù),為每個請求分配一個鉤子函數(shù)。
callback_function會接受一個數(shù)據(jù)塊作為它的第一個參數(shù)。print_url 函數(shù)就會以response作為第一個參數(shù)。
若回調(diào)函數(shù)返回一個值,默認以該值替換傳進來的數(shù)據(jù)(response)。若函數(shù)未返回任何東西, 也沒有什么其他的影響。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容