A connection pool is a container for a collection of connections to a specific host.

If you need to make requests to the same host repeatedly, then you should use a HTTPConnectionPool.

>>> from urllib3 import HTTPConnectionPool
>>> pool = HTTPConnectionPool('', maxsize=1)
>>> r = pool.request('GET', '/ajax/services/search/web',
...                  fields={'q': 'urllib3', 'v': '1.0'})
>>> r.status
>>> r.headers['content-type']
'text/javascript; charset=utf-8'
>>> len( # Content of the response
>>> r = pool.request('GET', '/ajax/services/search/web',
...                  fields={'q': 'python', 'v': '1.0'})
>>> len( # Content of the response
>>> pool.num_connections
>>> pool.num_requests

By default, the pool will cache just one connection. If you’re planning on using such a pool in a multithreaded environment, you should set the maxsize of the pool to a higher number, such as the number of threads. You can also control many other variables like timeout, blocking, and default headers.


There are various helper functions provided for instantiating these ConnectionPools more easily:

urllib3.connectionpool.connection_from_url(url, **kw)

Given a url, return an ConnectionPool instance of its host.

This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an ConnectionPool instance.

  • url – Absolute URL string that must include the scheme. Port is optional.
  • **kw – Passes additional parameters to the constructor of the appropriate ConnectionPool. Useful for specifying things like timeout, maxsize, headers, etc.


>>> conn = connection_from_url('')
>>> r = conn.request('GET', '/')
urllib3.connectionpool.make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None)

Shortcuts for generating request headers.

  • keep_alive – If True, adds ‘connection: keep-alive’ header.
  • accept_encoding – Can be a boolean, list, or string. True translates to ‘gzip,deflate’. List will get joined by comma. String will be used as provided.
  • user_agent – String representing the user-agent you want, such as “python-urllib3/0.6”
  • basic_auth – Colon-separated username:password string for ‘authorization: basic ...’ auth header.


>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}


urllib3.connectionpool comes with two connection pools:

class urllib3.connectionpool.HTTPConnectionPool(host, port=None, strict=False, timeout=None, maxsize=1, block=False, headers=None)

Thread-safe connection pool for one host.

  • host – Host used for this HTTP Connection (e.g. “localhost”), passed into httplib.HTTPConnection.
  • port – Port used for this HTTP Connection (None is equivalent to 80), passed into httplib.HTTPConnection.
  • strict – Causes BadStatusLine to be raised if the status line can’t be parsed as a valid HTTP/1.0 or 1.1 status line, passed into httplib.HTTPConnection.
  • timeout – Socket timeout for each individual connection, can be a float. None disables timeout.
  • maxsize – Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If block is set to false, more connections will be created but they will not be saved once they’ve been used.
  • block – If set to True, no more than maxsize connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding.
  • headers – Headers to include with all requests, unless other headers are given explicitly.
get_url(url, fields=None, **urlopen_kw)

Deprecated since version 1.0.

Use request() instead.


Check if the given url is a member of the same host as this conncetion pool.

post_url(url, fields=None, headers=None, **urlopen_kw)

Deprecated since version 1.0.

Use request() instead.

request(method, url, fields=None, headers=None, **urlopen_kw)

Make a request using urlopen() with the appropriate encoding of fields based on the method used.

This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as request_encode_url(), request_encode_body(), or even the lowest level urlopen().

request_encode_body(method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw)

Make a request using urlopen() with the fields encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc.

When encode_multipart=True (default), then urllib3.filepost.encode_multipart_formdata() is used to encode the payload with the appropriate content type. Otherwise urllib.urlencode() is used with the ‘application/x-www-form-urlencoded’ content type.

Multipart encoding must be used when posting files, and it’s reasonably safe to use it in other times too. However, it may break request signing, such as with OAuth.

Supports an optional fields parameter of key/value strings AND key/filetuple. A filetuple is a (filename, data) tuple. For example:

fields = {
    'foo': 'bar',
    'fakefile': ('foofile.txt', 'contents of foofile'),
    'realfile': ('barfile.txt', open('realfile').read()),
    'nonamefile': ('contents of nonamefile field'),

When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimick behavior of browsers.

Note that if headers are supplied, the ‘Content-Type’ header will be overwritten because it depends on the dynamic random boundary string which is used to compose the body of the request. The random boundary string can be explicitly set with the multipart_boundary parameter.

request_encode_url(method, url, fields=None, **urlopen_kw)

Make a request using urlopen() with the fields encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.

urlopen(method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, timeout=<object object at 0x7f7bbed93410>, pool_timeout=None, release_conn=None, **response_kw)

Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you’ll need to specify all the raw details.


More commonly, it’s appropriate to use a convenience method provided by RequestMethods, such as request().

  • method – HTTP request method (such as GET, POST, PUT, etc.)
  • body – Data to send in the request body (useful for creating POST requests, see HTTPConnectionPool.post_url for more convenience).
  • headers – Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers.
  • retries – Number of retries to allow before raising a MaxRetryError exception.
  • redirect – Automatically handle redirects (status codes 301, 302, 303, 307), each redirect counts as a retry.
  • assert_same_host – If True, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When False, you can use the pool on an HTTP proxy and request foreign hosts.
  • timeout – If specified, overrides the default timeout for this one request.
  • pool_timeout – If set and the pool is set to block=True, then this method will block for pool_timeout seconds and raise EmptyPoolError if no connection is available within the time period.
  • release_conn – If False, then the urlopen call will not release the connection back into the pool once a response is received. This is useful if you’re not preloading the response’s content immediately. You will need to call r.release_conn() on the response r to return the connection back into the pool. If None, it takes the value of response_kw.get('preload_content', True).
  • **response_kw – Additional parameters are passed to urllib3.response.HTTPResponse.from_httplib()
class urllib3.connectionpool.HTTPSConnectionPool(host, port=None, strict=False, timeout=None, maxsize=1, block=False, headers=None, key_file=None, cert_file=None, cert_reqs='CERT_NONE', ca_certs=None)

Same as HTTPConnectionPool, but HTTPS.

When Python is compiled with the ssl module, then VerifiedHTTPSConnection is used, which can verify certificates, instead of :class:httplib.HTTPSConnection`.

The key_file, cert_file, cert_reqs, and ca_certs parameters are only used if ssl is available and are fed into ssl.wrap_socket() to upgrade the connection socket into an SSL socket.

All of these pools inherit from a common base class:

class urllib3.connectionpool.ConnectionPool

Base class for all connection pools, such as HTTPConnectionPool and HTTPSConnectionPool.

Table Of Contents

Previous topic

urllib3 Documentation

Next topic


This Page