Urllib3 is a powerful, well-organized, Python library for HTTP clients , and many Python -native systems already use urllib3 . Urllib3 provides many important features not found in the python standard library:
1. Thread safety
2. Connection pool
3. Client SSL/TLS verification
4. File partial encoding upload
5. Assist in handling duplicate requests and HTTP relocations
6. Support compression encoding
7. Support HTTP and SOCKS proxy
8. 100% test coverage
Urllib3 is very powerful, but very simple to use:
Install:
Urllib3 can be installed via pip :
$pip install urllib3
You can also download the latest source code on github , unzip it and install it:
$git clone git://github.com/shazow/urllib3.git
$python setup.py install
Use of urllib3 :
Generate a request (request):
First, you have to import the urllib3 module:
Then you need a PoolManager instance to generate the request , and this instance object handles the connection to the thread pool and all the details of thread safety, without any manual manipulation:
Create a request with the request() method:
The request() method returns an HTTPResponse object.
You can also add some other information to the request via the request() method, such as :
The data item (request data) in the request ( request) can include:
Headers:
In the request() method, you can define a dictionary type and pass it as the headers parameter:
Query parameters:
对于GET、HEAD和DELETE请求,可以简单的通过定义一个字典类型作为fields参数传入即可:
对于POST和PUT请求(request),需要手动对传入数据进行编码,然后加在URL之后:
Form data:
对于PUT和POST请求(request),urllib3会自动将字典类型的field参数编码成表格类型.
JSON:
在发起请求时,可以通过定义body 参数并定义headers的Content-Type参数来发送一个已经过编译的JSON数据:
Files & binary data:
使用multipart/form-data编码方式上传文件,可以使用和传入Form data数据一样的方法进行,并将文件定义为一个元组的形式 (file_name,file_data):
文件名(filename)的定义不是严格要求的,但是推荐使用,以使得表现得更像浏览器。同时,还可以向元组中再增加一个数据来定义文件的 MIME类型:
如果是发送原始二进制数据,只要将其定义为body参数即可。同时,建议对header的Content-Type参数进行设置:
Timeout :
使用timeout,可以控制请求的运行时间。在一些简单的应用中,可以将timeout参数设置为一个浮点数:
要进行更精细的控制,可以使用Timeout实例,将连接的timeout和读的timeout分开设置:
如果想让所有的request都遵循一个timeout,可以将timeout参数定义在PoolManager中:
或者
当在具体的request中再次定义timeout时,会覆盖PoolManager层面上的timeout。
请求重试(retrying requests):
Urllib3 可以自动重试幂等请求,原理和handles redirect一样。可以通过设置retries参数对重试进行控制。Urllib3默认进行3次请求重 试,并进行3次方向改变。
给retries参数定义一个整型来改变请求重试的次数:
关闭请求重试(retrying request)及重定向(redirect)只要将retries定义为False即可:
关闭重定向(redirect)但保持重试(retrying request),将redirect参数定义为False即可:
要进行更精细的控制,可以使用retry实例,通过该实例可以对请求的重试进行更精细的控制。
例如,进行3次请求重试,但是只进行2次重定向:
如果想让所有请求都遵循一个retry策略,可以在PoolManager中定义retry参数:
或者
当在具体的request中再次定义retry时,会覆盖 PoolManager层面上的retry。