Connection Pools

class urllib3.HTTPConnectionPool(host, port=None, timeout=_TYPE_DEFAULT.token, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, _proxy_config=None, resolver=None, happy_eyeballs=False, **conn_kw)

Bases: ConnectionPool, RequestMethods

Thread-safe connection pool for one host.

Parameters:
  • host (str) – Host used for this HTTP Connection (e.g. “localhost”), passed into http.client.HTTPConnection.

  • port (int | None) – Port used for this HTTP Connection (None is equivalent to 80), passed into http.client.HTTPConnection.

  • timeout (_TYPE_TIMEOUT | None) – 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 (int) – 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 (bool) – 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 (Mapping[str, str] | None) – Headers to include with all requests, unless other headers are given explicitly.

  • retries (Retry | bool | int | None) – Retry configuration to use by default with requests in this pool.

  • _proxy (Url | None) – Parsed proxy URL, should not be used directly, instead, see urllib3.ProxyManager

  • _proxy_headers (Mapping[str, str] | None) – A dictionary with proxy headers, should not be used directly, instead, see urllib3.ProxyManager

  • **conn_kw (Any) – Additional parameters are used to create fresh urllib3.connection.HTTPConnection, urllib3.connection.HTTPSConnection instances.

  • _proxy_config (ProxyConfig | None)

  • resolver (ResolverDescription | list[ResolverDescription] | str | list[str] | BaseResolver | None)

  • happy_eyeballs (bool | int)

  • **conn_kw

ConnectionCls

alias of HTTPConnection

close()

Close all pooled connections and disable the pool.

Return type:

None

get_response(*, promise=None)

Retrieve the first response available in the pool. This method should be called after issuing at least one request with multiplexed=True. If none available, return None.

Parameters:

promise (ResponsePromise | None)

Return type:

HTTPResponse | None

property is_idle: bool
is_same_host(url)

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

Parameters:

url (str)

Return type:

bool

scheme: str | None = 'http'
urlopen(method: str, url: str, body: bytes | IO[Any] | Iterable[bytes] | Iterable[str] | str | LowLevelResponse | AsyncLowLevelResponse | None = None, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, redirect: bool = True, assert_same_host: bool = True, timeout: float | _TYPE_DEFAULT | Timeout | 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, on_post_connection: Callable[[ConnectionInfo], None] | None = None, on_upload_body: Callable[[int, int | None, bool, bool], None] | None = None, on_early_response: Callable[[HTTPResponse], None] | None = None, extension: ExtensionFromHTTP | None = None, *, multiplexed: Literal[False] = False, **response_kw: Any) HTTPResponse
urlopen(method: str, url: str, body: bytes | IO[Any] | Iterable[bytes] | Iterable[str] | str | LowLevelResponse | AsyncLowLevelResponse | None = None, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, redirect: bool = True, assert_same_host: bool = True, timeout: float | _TYPE_DEFAULT | Timeout | 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, on_post_connection: Callable[[ConnectionInfo], None] | None = None, on_upload_body: Callable[[int, int | None, bool, bool], None] | None = None, on_early_response: Callable[[HTTPResponse], None] | None = None, extension: ExtensionFromHTTP | None = None, *, multiplexed: Literal[True], **response_kw: Any) ResponsePromise

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 of str/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 a Retry 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. 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. 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 response r to return the connection back into the pool. If None, it takes the value of preload_content which defaults to True.

  • 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.

  • on_post_connection – Callable to be invoked that will inform you of the connection specifications for the request to be sent. See urllib3.ConnectionInfo class for more.

  • on_upload_body – Callable that will be invoked upon body upload in order to be able to track the progress. The values are expressed in bytes. It is possible that the total isn’t available, thus set to None. In order, arguments are: (total_sent, total_to_be_sent, completed, any_error)

  • on_early_response – Callable that will be invoked upon early responses, can be invoked one or several times. All informational responses except HTTP/102 (Switching Protocol) are concerned here. The callback takes only one positional argument, the fully constructed HTTPResponse. Those responses never have bodies, only headers.

  • multiplexed – Dispatch the request in a non-blocking way, this means that the response will be retrieved in the future with the get_response() method.

class urllib3.HTTPSConnectionPool(host, port=None, timeout=_TYPE_DEFAULT.token, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, ssl_version=None, ssl_minimum_version=None, ssl_maximum_version=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, ca_cert_data=None, cert_data=None, key_data=None, **conn_kw)

Bases: HTTPConnectionPool

Same as HTTPConnectionPool, but HTTPS.

HTTPSConnection uses one of assert_fingerprint, assert_hostname and host in this order to verify connections. If assert_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 if ssl is available and are fed into urllib3.util.ssl_wrap_socket() to upgrade the connection socket into an SSL socket.

Parameters:
ConnectionCls

alias of HTTPSConnection

scheme: str | None = 'https'
class urllib3.connectionpool.ConnectionPool(host, port=None)

Bases: object

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

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.

Parameters:
  • host (str)

  • port (int | None)

QueueCls

alias of TrafficPolice

close()

Close all pooled connections and disable the pool.

Return type:

None

property is_idle: bool
scheme: str | None = None
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.

Parameters:
  • url (str) – Absolute URL string that must include the scheme. Port is optional.

  • **kw (Any) – Passes additional parameters to the constructor of the appropriate ConnectionPool. Useful for specifying things like timeout, maxsize, headers, etc.

Return type:

HTTPConnectionPool

Example:

>>> conn = connection_from_url('http://google.com/')
>>> r = conn.request('GET', '/')
class urllib3.AsyncHTTPConnectionPool(host, port=None, timeout=_TYPE_DEFAULT.token, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, _proxy_config=None, resolver=None, happy_eyeballs=False, **conn_kw)

Bases: AsyncConnectionPool, AsyncRequestMethods

Task-safe async connection pool for one host.

Parameters:
  • host (str) – Host used for this HTTP Connection (e.g. “localhost”), passed into http.client.HTTPConnection.

  • port (int | None) – Port used for this HTTP Connection (None is equivalent to 80), passed into http.client.HTTPConnection.

  • timeout (_TYPE_TIMEOUT | None) – 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 (int) – 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 (bool) – 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 (Mapping[str, str] | None) – Headers to include with all requests, unless other headers are given explicitly.

  • retries (Retry | bool | int | None) – Retry configuration to use by default with requests in this pool.

  • _proxy (Url | None) – Parsed proxy URL, should not be used directly, instead, see urllib3.ProxyManager

  • _proxy_headers (Mapping[str, str] | None) – A dictionary with proxy headers, should not be used directly, instead, see urllib3.AsyncProxyManager

  • **conn_kw (Any) – Additional parameters are used to create fresh urllib3._async.connection.AsyncHTTPConnection, urllib3._async.connection.AsyncHTTPSConnection instances.

  • _proxy_config (ProxyConfig | None)

  • resolver (AsyncResolverDescription | list[AsyncResolverDescription] | str | list[str] | AsyncBaseResolver | None)

  • happy_eyeballs (bool | int)

  • **conn_kw

ConnectionCls

alias of AsyncHTTPConnection

async close()

Close all pooled connections and disable the pool.

Return type:

None

async get_response(*, promise=None)

Retrieve the first response available in the pool. This method should be called after issuing at least one request with multiplexed=True. If none available, return None.

Parameters:

promise (ResponsePromise | None)

Return type:

AsyncHTTPResponse | None

property is_idle: bool
is_same_host(url)

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

Parameters:

url (str)

Return type:

bool

scheme: str | None = 'http'
async urlopen(method: str, url: str, body: bytes | IO[Any] | Iterable[bytes] | Iterable[str] | str | LowLevelResponse | AsyncLowLevelResponse | AsyncIterable[bytes] | AsyncIterable[str] | None = None, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, redirect: bool = True, assert_same_host: bool = True, timeout: float | _TYPE_DEFAULT | Timeout | 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, on_post_connection: Callable[[ConnectionInfo], Awaitable[None]] | None = None, on_upload_body: Callable[[int, int | None, bool, bool], Awaitable[None]] = None, on_early_response: Callable[[AsyncHTTPResponse], Awaitable[None]] | None = None, extension: AsyncExtensionFromHTTP | None = None, *, multiplexed: Literal[False] = False, **response_kw: Any) AsyncHTTPResponse
async urlopen(method: str, url: str, body: bytes | IO[Any] | Iterable[bytes] | Iterable[str] | str | LowLevelResponse | AsyncLowLevelResponse | AsyncIterable[bytes] | AsyncIterable[str] | None = None, headers: Mapping[str, str] | None = None, retries: Retry | bool | int | None = None, redirect: bool = True, assert_same_host: bool = True, timeout: float | _TYPE_DEFAULT | Timeout | 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, on_post_connection: Callable[[ConnectionInfo], Awaitable[None]] | None = None, on_upload_body: Callable[[int, int | None, bool, bool], Awaitable[None]] = None, on_early_response: Callable[[AsyncHTTPResponse], Awaitable[None]] | None = None, extension: AsyncExtensionFromHTTP | None = None, *, multiplexed: Literal[True], **response_kw: Any) ResponsePromise

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 of str/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 a Retry 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. 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. 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 response r to return the connection back into the pool. If None, it takes the value of preload_content which defaults to True.

  • 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.

  • on_post_connection – Callable to be invoked that will inform you of the connection specifications for the request to be sent. See urllib3.ConnectionInfo class for more.

  • on_upload_body – Callable that will be invoked upon body upload in order to be able to track the progress. The values are expressed in bytes. It is possible that the total isn’t available, thus set to None. In order, arguments are: (total_sent, total_to_be_sent, completed, any_error)

  • on_early_response – Callable that will be invoked upon early responses, can be invoked one or several times. All informational responses except HTTP/102 (Switching Protocol) are concerned here. The callback takes only one positional argument, the fully constructed HTTPResponse. Those responses never have bodies, only headers.

  • multiplexed – Dispatch the request in a non-blocking way, this means that the response will be retrieved in the future with the get_response() method.

class urllib3.AsyncHTTPSConnectionPool(host, port=None, timeout=_TYPE_DEFAULT.token, maxsize=1, block=False, headers=None, retries=None, _proxy=None, _proxy_headers=None, key_file=None, cert_file=None, cert_reqs=None, key_password=None, ca_certs=None, ssl_version=None, ssl_minimum_version=None, ssl_maximum_version=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None, ca_cert_data=None, cert_data=None, key_data=None, **conn_kw)

Bases: AsyncHTTPConnectionPool

Same as HTTPConnectionPool, but HTTPS.

HTTPSConnection uses one of assert_fingerprint, assert_hostname and host in this order to verify connections. If assert_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 if ssl is available and are fed into urllib3.util.ssl_wrap_socket() to upgrade the connection socket into an SSL socket.

Parameters:
ConnectionCls

alias of AsyncHTTPSConnection

scheme: str | None = 'https'
urllib3.async_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.

Parameters:
  • url (str) – Absolute URL string that must include the scheme. Port is optional.

  • kw (Any) – Passes additional parameters to the constructor of the appropriate ConnectionPool. Useful for specifying things like timeout, maxsize, headers, etc.

Return type:

AsyncHTTPConnectionPool

Example:

>>> conn = connection_from_url('http://google.com/')
>>> r = conn.request('GET', '/')