URLLIB3 基本用法

基本用法

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()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,324评论 19 139
  • Spring Web MVC Spring Web MVC 是包含在 Spring 框架中的 Web 框架,建立于...
    Hsinwong阅读 22,675评论 1 92
  • JDBC基础知识 一、采用JDBC访问数据库的基本步骤: A.载入JDBC驱动程序 B.定义连接URL ...
    91数据阅读 9,325评论 0 20
  • 他的学习不是多么好,只是中等,在班里是一个可有可无的人物。 数学课上老师写了一道很难的题。大家纷纷...
    甜酱吖阅读 1,222评论 0 0
  • 【Chapter 22 好感】 汤皖皖得了重感冒,可以说是她22年来的第一次重感冒。 这次感冒才让她知道原来以前的...
    不爱吃胡萝卜的兔子小姐o阅读 1,553评论 0 0