URLLIB3 基本用法

作者: 贾磊_cd | 来源:发表于2018-09-13 16:03 被阅读7次

    基本用法

    Request

    您需要一个PoolManager实例来发出请求。 此对象处理连接池和线程安全的所有详细信息:

    1. 创建一个poolManager
    2. 使用poolManager的request()发送数据包
      它的返回是是一个HTTPResponse对象,可以使用这个request发送各种格式的HTTP请求
      PoolManager ---- 允许任意请求,同时透明地跟踪您所需的连接池。
    http = urllib3.PoolManager()
    r = http.request('GET', 'http://httpbin.org/robots.txt')
    r = http.request('POST', 'http://httpbin.org/post', fields={'hello': 'world'})
    

    HTTPResponse包含

    • status
    • data
    • header

    Request Data

    您可以在headers参数指定一个字典为header

    r = http.request('GET', 'http://httpbin.org/headers', headers={'X-Something': 'value'}) 
    

    对于GET,HEAD和DELETE请求,您只需将query参数作为字典传入fields参数

    r = http.request('GET','http://httpbin.org/get',fields={'arg': 'value'})
    

    对于POST,PUT请求, 如果是需要在URL中加入参数,那么需要进行
    手动编码

    from urllib.parse import urlencode
    encoded_args = urlencode({'arg': 'value'})
    url = 'http://httpbin.org/post?' + encoded_args
    r = http.request('POST', url)
    

    如果使用form data 作为POST的参数,怎么可以直接在field中填入参数。

    r = http.request('POST','http://httpbin.org/post',fields={'field': 'value'})
    

    也可以指定一个json对象作为POST的body,但是这时需要设置
    Content-Type为 application/json

    data = {'attribute': 'value'}
    encoded_data = json.dumps(data).encode('utf-8')
    r = http.request('POST', 'http://httpbin.org/post', body=encoded_data, headers={'Content-Type': 'application/json'})
    

    发送文件, 首先读入文件,然后使用fields来传送数据

    with open('example.txt') as fp:
    ... file_data = fp.read()
    r = http.request('POST', 'http://httpbin.org/post', fields={'filefield': ('example.txt', file_data),})
    

    对HTTPS的支持

    默认urllib3不去比verify HTTPS requests
    如果需要验证的话需要安装certifi,并且在创建PoolManager的时候加入certifi

    pip install certifi
    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED',ca_certs=certifi.where())
    

    如果证书验证失败就会raise SSLError

    使用Timeout,

    1. request函数可以加入一个timeout参数
    2. 使用TimeOut对象, 这是可以指定connect timeout,或者read timeout
    3. 直接为PoolManager指定一个timeout
    http.request('GET', 'http://httpbin.org/delay/3', timeout=urllib3.Timeout(connect=1.0, read=2.0))
    http = urllib3.PoolManager(timeout=3.0)
    http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=1.0, read=2.0))
    

    urllib3可以自动重试幂等请求 (同样的机制也处理重定向)

    指定request函数中的retries参数(默认会re-try3次)

    http.requests('GET', 'http://httpbin.org/ip', retries=10)
    

    这个参数也可以指定给PoolManager

    高级用法

    PoolManager 会自动创建ConnectionPool,默认会keep最多10个ConnectionPool实例
    如果需要连接更多的host,那么可以加大这个max pool

    http = urllib3.PoolManager(num_pools=50)
    

    同样,ConnectionPool类保留一个单独的HTTPConnection实例池。 这些连接在单个请求期间使用,并在请求完成时返回到池中。 默认情况下,只保存一个连接以供重复使用。 如果您同时向同一主机发出许多请求,则可能会提高性能以增加此数量:

    http = urllib3.PoolManager(maxsize=10)
    http = urllib3.HTTPConnectionPool('google.com', maxsize=10)
    HTTPConnectionPool 针对一个特定的host产出连接
    

    ConnectionPool的池的行为与PoolManager不同。 默认情况下,如果发出新请求且池中没有空闲连接,则将创建新连接。 但是,如果存在多个maxsize连接,则不会保存此连接。 这意味着maxsize不确定可以向特定主机打开的最大连接数,而只是确定要保留在池中的最大连接数。 但是,如果指定block = True,则最多可以打开特定主机的maxsize连接:

    Proxies

    通过ProxyManager来使用http proxy,用法就和PoolManager一样

    proxy = urllib3.ProxyManager('http://localhost:3128/')
    proxy.request('GET', 'http://google.com/')
    

    这里直接通过proxy去发送请求
    如果使用socks5的话需要使用SOCKProxyManager,这时需要安装pysocks 包

    from urllib3.contrib.socks import SOCKSProxyManager
    proxy = SOCKSProxyManager('socks5://localhost:8889/')
    proxy.request('GET', 'http://google.com/')
    

    取消https的验证

    urllib3.disable_warnings()
    

    相关文章

      网友评论

        本文标题:URLLIB3 基本用法

        本文链接:https://www.haomeiwen.com/subject/xrowgftx.html