python requestsライブラリ

3192 ワード

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
いくつかの高度な使い方:
  • 多用セッション
  • 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)がデフォルトで置き換えられます.関数が何も返されなければ、他の影響はありません.