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('ajax.googleapis.com', maxsize=1)
>>> r = pool.request('GET', '/ajax/services/search/web',
... fields={'q': 'urllib3', 'v': '1.0'})
>>> r.status
200
>>> r.headers['content-type']
'text/javascript; charset=utf-8'
>>> len(r.data) # Content of the response
3318
>>> r = pool.request('GET', '/ajax/services/search/web',
... fields={'q': 'python', 'v': '1.0'})
>>> len(r.data) # Content of the response
2960
>>> pool.num_connections
1
>>> pool.num_requests
2
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: str, **kw: Any) HTTPConnectionPool [source]¶
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.
- Parameters:
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.Example:
>>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/')
urllib3.connectionpool
comes with two connection pools:
- class urllib3.connectionpool.HTTPConnectionPool(host: str, port: int | None = None, timeout: Timeout | float | _TYPE_DEFAULT | None = _TYPE_DEFAULT.token, maxsize: int = 1, block: bool = False, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, _proxy: Url | None = None, _proxy_headers: Mapping[str, str] | None = None, _proxy_config: ProxyConfig | None = None, **conn_kw: Any)[source]¶
Thread-safe connection pool for one host.
- Parameters:
host – Host used for this HTTP Connection (e.g. “localhost”), passed into
http.client.HTTPConnection
.port – Port used for this HTTP Connection (None is equivalent to 80), passed into
http.client.HTTPConnection
.timeout – Socket timeout in seconds for each individual connection. This can be a float or integer, which sets the timeout for the HTTP request, or an instance of
urllib3.util.Timeout
which gives you more fine-grained control over request timeouts. After the constructor has been parsed, this is always a urllib3.util.Timeout object.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.
retries – Retry configuration to use by default with requests in this pool.
_proxy – Parsed proxy URL, should not be used directly, instead, see
urllib3.ProxyManager
_proxy_headers – A dictionary with proxy headers, should not be used directly, instead, see
urllib3.ProxyManager
**conn_kw – Additional parameters are used to create fresh
urllib3.connection.HTTPConnection
,urllib3.connection.HTTPSConnection
instances.
- ConnectionCls¶
alias of
HTTPConnection
- QueueCls¶
alias of
LifoQueue
- is_same_host(url: str) bool [source]¶
Check if the given
url
is a member of the same host as this connection pool.
- request(method: str, url: str, body: bytes | IO[Any] | Iterable[bytes] | str | None = None, fields: Sequence[Tuple[str, str | bytes | Tuple[str, str | bytes] | Tuple[str, str | bytes, str]] | RequestField] | Mapping[str, str | bytes | Tuple[str, str | bytes] | Tuple[str, str | bytes, str]] | None = None, headers: Mapping[str, str] | None = None, json: Any | None = None, **urlopen_kw: Any) BaseHTTPResponse ¶
Make a request using
urlopen()
with the appropriate encoding offields
based on themethod
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 levelurlopen()
.
- request_encode_body(method: str, url: str, fields: Sequence[Tuple[str, str | bytes | Tuple[str, str | bytes] | Tuple[str, str | bytes, str]] | RequestField] | Mapping[str, str | bytes | Tuple[str, str | bytes] | Tuple[str, str | bytes, str]] | None = None, headers: Mapping[str, str] | None = None, encode_multipart: bool = True, multipart_boundary: str | None = None, **urlopen_kw: str) BaseHTTPResponse ¶
Make a request using
urlopen()
with thefields
encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc.When
encode_multipart=True
(default), thenurllib3.encode_multipart_formdata()
is used to encode the payload with the appropriate content type. Otherwiseurllib.parse.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, MIME type) tuple where the MIME type is optional. For example:fields = { 'foo': 'bar', 'fakefile': ('foofile.txt', 'contents of foofile'), 'realfile': ('barfile.txt', open('realfile').read()), 'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'), 'nonamefile': 'contents of nonamefile field', }When uploading a file, providing a filename (the first parameter of the tuple) is optional but recommended to best mimic 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 themultipart_boundary
parameter.
- request_encode_url(method: str, url: str, fields: Sequence[Tuple[str, str | bytes]] | Mapping[str, str | bytes] | None = None, headers: Mapping[str, str] | None = None, **urlopen_kw: str) BaseHTTPResponse ¶
Make a request using
urlopen()
with thefields
encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.
- urlopen(method: str, url: str, body: bytes | IO[Any] | Iterable[bytes] | str | None = None, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, redirect: bool = True, assert_same_host: bool = True, timeout: Timeout | float | _TYPE_DEFAULT | None = _TYPE_DEFAULT.token, pool_timeout: int | None = None, release_conn: bool | None = None, chunked: bool = False, body_pos: int | _TYPE_FAILEDTELL | None = None, preload_content: bool = True, decode_content: bool = True, **response_kw: Any) BaseHTTPResponse [source]¶
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.
Note
More commonly, it’s appropriate to use a convenience method such as
request()
.Note
release_conn will only behave as expected if preload_content=False because we want to make preload_content=False the default behaviour someday soon without breaking backwards compatibility.
- Parameters:
method – HTTP request method (such as GET, POST, PUT, etc.)
url – The URL to perform the request on.
body – Data to send in the request body, either
str
,bytes
, an iterable ofstr
/bytes
, or a file-like object.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 (
Retry
, False, or an int.) –Configure the number of retries to allow before raising a
MaxRetryError
exception.Pass
None
to retry until you receive a response. Pass aRetry
object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry.If
False
, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned.redirect – If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too.
assert_same_host – If
True
, will make sure that the host of the pool requests is consistent else will raise HostChangedError. WhenFalse
, you can use the pool on an HTTP proxy and request foreign hosts.timeout – If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of
urllib3.util.Timeout
.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.preload_content (bool) – If True, the response’s body will be preloaded into memory.
decode_content (bool) – If True, will attempt to decode the body based on the ‘content-encoding’ header.
release_conn – If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when preload_content=True). This is useful if you’re not preloading the response’s content immediately. You will need to call
r.release_conn()
on the responser
to return the connection back into the pool. If None, it takes the value ofpreload_content
which defaults toTrue
.chunked (bool) – If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False.
body_pos (int) – Position to seek to in file-like body in the event of a retry or redirect. Typically this won’t need to be set because urllib3 will auto-populate the value when needed.
- class urllib3.connectionpool.HTTPSConnectionPool(host: str, port: int | None = None, timeout: _TYPE_TIMEOUT | None = _TYPE_DEFAULT.token, maxsize: int = 1, block: bool = False, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, _proxy: Url | None = None, _proxy_headers: Mapping[str, str] | None = None, key_file: str | None = None, cert_file: str | None = None, cert_reqs: int | str | None = None, key_password: str | None = None, ca_certs: str | None = None, ssl_version: int | str | None = None, ssl_minimum_version: ssl.TLSVersion | None = None, ssl_maximum_version: ssl.TLSVersion | None = None, assert_hostname: str | Literal[False] | None = None, assert_fingerprint: str | None = None, ca_cert_dir: str | None = None, **conn_kw: Any)[source]¶
Same as
HTTPConnectionPool
, but HTTPS.
HTTPSConnection
uses one ofassert_fingerprint
,assert_hostname
andhost
in this order to verify connections. Ifassert_hostname
is False, no verification is done.The
key_file
,cert_file
,cert_reqs
,ca_certs
,ca_cert_dir
,ssl_version
,key_password
are only used ifssl
is available and are fed intourllib3.util.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(host: str, port: int | None = None)[source]¶
Base class for all connection pools, such as
HTTPConnectionPool
andHTTPSConnectionPool
.Note
ConnectionPool.urlopen() does not normalize or percent-encode target URIs which is useful if your target server doesn’t support percent-encoded target URIs.