Helpers

Useful methods for working with httplib, completely decoupled from code specific to urllib3.

Utilities

class urllib3.util.Retry(total: bool | int | None = 10, connect: int | None = None, read: int | None = None, redirect: bool | int | None = None, status: int | None = None, other: int | None = None, allowed_methods: Collection[str] | None = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}), status_forcelist: Collection[int] | None = None, backoff_factor: float = 0, backoff_max: float = 120, raise_on_redirect: bool = True, raise_on_status: bool = True, history: tuple[urllib3.util.retry.RequestHistory, ...] | None = None, respect_retry_after_header: bool = True, remove_headers_on_redirect: Collection[str] = frozenset({'Authorization'}), backoff_jitter: float = 0.0)[source]

Retry configuration.

Each retry attempt will create a new Retry object with updated values, so they can be safely reused.

Retries can be defined as a default for a pool:

retries = Retry(connect=5, read=2, redirect=5)
http = PoolManager(retries=retries)
response = http.request("GET", "https://example.com/")

Or per-request (which overrides the default for the pool):

response = http.request("GET", "https://example.com/", retries=Retry(10))

Retries can be disabled by passing False:

response = http.request("GET", "https://example.com/", retries=False)

Errors will be wrapped in MaxRetryError unless retries are disabled, in which case the causing exception will be raised.

Parameters:
  • total (int) –

    Total number of retries to allow. Takes precedence over other counts.

    Set to None to remove this constraint and fall back on other counts.

    Set to 0 to fail on the first retry.

    Set to False to disable and imply raise_on_redirect=False.

  • connect (int) –

    How many connection-related errors to retry on.

    These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request.

    Set to 0 to fail on the first retry of this type.

  • read (int) –

    How many times to retry on read errors.

    These errors are raised after the request was sent to the server, so the request may have side-effects.

    Set to 0 to fail on the first retry of this type.

  • redirect (int) –

    How many redirects to perform. Limit this to avoid infinite redirect loops.

    A redirect is a HTTP response with a status code 301, 302, 303, 307 or 308.

    Set to 0 to fail on the first retry of this type.

    Set to False to disable and imply raise_on_redirect=False.

  • status (int) –

    How many times to retry on bad status codes.

    These are retries made on responses, where status code matches status_forcelist.

    Set to 0 to fail on the first retry of this type.

  • other (int) –

    How many times to retry on other errors.

    Other errors are errors that are not connect, read, redirect or status errors. These errors might be raised after the request was sent to the server, so the request might have side-effects.

    Set to 0 to fail on the first retry of this type.

    If total is not set, it’s a good idea to set this to 0 to account for unexpected edge cases and avoid infinite retry loops.

  • allowed_methods (Collection) –

    Set of uppercased HTTP method verbs that we should retry on.

    By default, we only retry on methods which are considered to be idempotent (multiple requests with the same parameters end with the same state). See Retry.DEFAULT_ALLOWED_METHODS.

    Set to a None value to retry on any verb.

  • status_forcelist (Collection) –

    A set of integer HTTP status codes that we should force a retry on. A retry is initiated if the request method is in allowed_methods and the response status code is in status_forcelist.

    By default, this is disabled with None.

  • backoff_factor (float) –

    A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). urllib3 will sleep for:

    {backoff factor} * (2 ** ({number of previous retries}))
    

    seconds. If backoff_jitter is non-zero, this sleep is extended by:

    random.uniform(0, {backoff jitter})
    

    seconds. For example, if the backoff_factor is 0.1, then Retry.sleep() will sleep for [0.0s, 0.2s, 0.4s, 0.8s, …] between retries. No backoff will ever be longer than backoff_max.

    By default, backoff is disabled (factor set to 0).

  • raise_on_redirect (bool) – Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range.

  • raise_on_status (bool) – Similar meaning to raise_on_redirect: whether we should raise an exception, or return a response, if status falls in status_forcelist range and retries have been exhausted.

  • history (tuple) – The history of the request encountered during each call to increment(). The list is in the order the requests occurred. Each list item is of class RequestHistory.

  • respect_retry_after_header (bool) – Whether to respect Retry-After header on status codes defined as Retry.RETRY_AFTER_STATUS_CODES or not.

  • remove_headers_on_redirect (Collection) – Sequence of headers to remove from the request when a response indicating a redirect is returned before firing off the redirected request.

DEFAULT_ALLOWED_METHODS = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'})

Default methods to be used for allowed_methods

DEFAULT_BACKOFF_MAX = 120

Default maximum backoff time.

DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset({'Authorization'})

Default headers to be used for remove_headers_on_redirect

RETRY_AFTER_STATUS_CODES = frozenset({413, 429, 503})

Default status codes to be used for status_forcelist

classmethod from_int(retries: Retry | bool | int | None, redirect: bool | int | None = True, default: Retry | bool | int | None = None) Retry[source]

Backwards-compatibility for the old retries format.

get_backoff_time() float[source]

Formula for computing the current backoff

Return type:

float

get_retry_after(response: BaseHTTPResponse) float | None[source]

Get the value of Retry-After in seconds.

increment(method: str | None = None, url: str | None = None, response: BaseHTTPResponse | None = None, error: Exception | None = None, _pool: ConnectionPool | None = None, _stacktrace: TracebackType | None = None) Retry[source]

Return a new Retry object with incremented retry counters.

Parameters:
  • response (BaseHTTPResponse) – A response object, or None, if the server did not return a response.

  • error (Exception) – An error encountered during the request, or None if the response was received successfully.

Returns:

A new Retry object.

is_exhausted() bool[source]

Are we out of retries?

is_retry(method: str, status_code: int, has_retry_after: bool = False) bool[source]

Is this method/status code retryable? (Based on allowlists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header)

sleep(response: BaseHTTPResponse | None = None) None[source]

Sleep between retry attempts.

This method will respect a server’s Retry-After response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately.

class urllib3.util.SSLContext(protocol=None, *args, **kwargs)[source]

An SSLContext holds various SSL-related configuration options and data, such as certificates and possibly a private key.

sslobject_class

alias of SSLObject

sslsocket_class

alias of SSLSocket

class urllib3.util.Timeout(total: float | _TYPE_DEFAULT | None = None, connect: float | _TYPE_DEFAULT | None = _TYPE_DEFAULT.token, read: float | _TYPE_DEFAULT | None = _TYPE_DEFAULT.token)[source]

Timeout configuration.

Timeouts can be defined as a default for a pool:

import urllib3

timeout = urllib3.util.Timeout(connect=2.0, read=7.0)

http = urllib3.PoolManager(timeout=timeout)

resp = http.request("GET", "https://example.com/")

print(resp.status)

Or per-request (which overrides the default for the pool):

response = http.request("GET", "https://example.com/", timeout=Timeout(10))

Timeouts can be disabled by setting all the parameters to None:

no_timeout = Timeout(connect=None, read=None)
response = http.request("GET", "https://example.com/", timeout=no_timeout)
Parameters:
  • total (int, float, or None) –

    This combines the connect and read timeouts into one; the read timeout will be set to the time leftover from the connect attempt. In the event that both a connect timeout and a total are specified, or a read timeout and a total are specified, the shorter timeout will be applied.

    Defaults to None.

  • connect (int, float, or None) – The maximum amount of time (in seconds) to wait for a connection attempt to a server to succeed. Omitting the parameter will default the connect timeout to the system default, probably the global default timeout in socket.py. None will set an infinite timeout for connection attempts.

  • read (int, float, or None) –

    The maximum amount of time (in seconds) to wait between consecutive read operations for a response from the server. Omitting the parameter will default the read timeout to the system default, probably the global default timeout in socket.py. None will set an infinite timeout.

Note

Many factors can affect the total amount of time for urllib3 to return an HTTP response.

For example, Python’s DNS resolver does not obey the timeout specified on the socket. Other factors that can affect total request time include high CPU load, high swap, the program running at a low priority level, or other behaviors.

In addition, the read and total timeouts only measure the time between read operations on the socket connecting the client and the server, not the total amount of time for the request to return a complete response. For most requests, the timeout is raised because the server has not sent the first byte in the specified time. This is not always the case; if a server streams one byte every fifteen seconds, a timeout of 20 seconds will not trigger, even though the request will take several minutes to complete.

If your goal is to cut off any request after a set amount of wall clock time, consider having a second “watcher” thread to cut off a slow request.

DEFAULT_TIMEOUT: float | _TYPE_DEFAULT | None = -1

A sentinel object representing the default timeout value

clone() Timeout[source]

Create a copy of the timeout object

Timeout properties are stored per-pool but each request needs a fresh Timeout object to ensure each one has its own start/stop configured.

Returns:

a copy of the timeout object

Return type:

Timeout

property connect_timeout: float | _TYPE_DEFAULT | None

Get the value to use when setting a connection timeout.

This will be a positive float or integer, the value None (never timeout), or the default system timeout.

Returns:

Connect timeout.

Return type:

int, float, Timeout.DEFAULT_TIMEOUT or None

classmethod from_float(timeout: float | _TYPE_DEFAULT | None) Timeout[source]

Create a new Timeout from a legacy timeout value.

The timeout value used by httplib.py sets the same timeout on the connect(), and recv() socket requests. This creates a Timeout object that sets the individual timeouts to the timeout value passed to this function.

Parameters:

timeout (integer, float, urllib3.util.Timeout.DEFAULT_TIMEOUT, or None) – The legacy timeout value.

Returns:

Timeout object

Return type:

Timeout

get_connect_duration() float[source]

Gets the time elapsed since the call to start_connect().

Returns:

Elapsed time in seconds.

Return type:

float

Raises:

urllib3.exceptions.TimeoutStateError – if you attempt to get duration for a timer that hasn’t been started.

property read_timeout: float | None

Get the value for the read timeout.

This assumes some time has elapsed in the connection timeout and computes the read timeout appropriately.

If self.total is set, the read timeout is dependent on the amount of time taken by the connect timeout. If the connection time has not been established, a TimeoutStateError will be raised.

Returns:

Value to use for the read timeout.

Return type:

int, float or None

Raises:

urllib3.exceptions.TimeoutStateError – If start_connect() has not yet been called on this object.

start_connect() float[source]

Start the timeout clock, used during a connect() attempt

Raises:

urllib3.exceptions.TimeoutStateError – if you attempt to start a timer that has been started already.

class urllib3.util.Url(scheme: str | None = None, auth: str | None = None, host: str | None = None, port: int | None = None, path: str | None = None, query: str | None = None, fragment: str | None = None)[source]

Data structure for representing an HTTP URL. Used as a return value for parse_url(). Both the scheme and host are normalized as they are both case-insensitive according to RFC 3986.

property authority: str | None

Authority component as defined in RFC 3986 3.2. This includes userinfo (auth), host and port.

i.e.

userinfo@host:port

property hostname: str | None

For backwards-compatibility with urlparse. We’re nice like that.

property netloc: str | None

Network location including host and port.

If you need the equivalent of urllib.parse’s netloc, use the authority property instead.

property request_uri: str

Absolute path including the query string.

property url: str

Convert self into a url

This function should more or less round-trip with parse_url(). The returned url may not be exactly the same as the url inputted to parse_url(), but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed).

Example:

import urllib3

U = urllib3.util.parse_url("https://google.com/mail/")

print(U.url)
# "https://google.com/mail/"

print( urllib3.util.Url("https", "username:password",
                        "host.com", 80, "/path", "query", "fragment"
                        ).url
    )
# "https://username:password@host.com:80/path?query#fragment"
urllib3.util.assert_fingerprint(cert: bytes | None, fingerprint: str) None[source]

Checks if given fingerprint matches the supplied certificate.

Parameters:
  • cert – Certificate as bytes object.

  • fingerprint – Fingerprint as string of hexdigits, can be interspersed by colons.

urllib3.util.create_urllib3_context(ssl_version: int | None = None, cert_reqs: int | None = None, options: int | None = None, ciphers: str | None = None, ssl_minimum_version: int | None = None, ssl_maximum_version: int | None = None) SSLContext[source]

Creates and configures an ssl.SSLContext instance for use with urllib3.

Parameters:
  • ssl_version

    The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support.

    This parameter is deprecated instead use ‘ssl_minimum_version’.

  • ssl_minimum_version – The minimum version of TLS to be used. Use the ‘ssl.TLSVersion’ enum for specifying the value.

  • ssl_maximum_version – The maximum version of TLS to be used. Use the ‘ssl.TLSVersion’ enum for specifying the value. Not recommended to set to anything other than ‘ssl.TLSVersion.MAXIMUM_SUPPORTED’ which is the default value.

  • cert_reqs – Whether to require the certificate verification. This defaults to ssl.CERT_REQUIRED.

  • options – Specific OpenSSL options. These default to ssl.OP_NO_SSLv2, ssl.OP_NO_SSLv3, ssl.OP_NO_COMPRESSION, and ssl.OP_NO_TICKET.

  • ciphers – Which cipher suites to allow the server to select. Defaults to either system configured ciphers if OpenSSL 1.1.1+, otherwise uses a secure default set of ciphers.

Returns:

Constructed SSLContext object with specified options

Return type:

SSLContext

urllib3.util.is_connection_dropped(conn: BaseHTTPConnection) bool[source]

Returns True if the connection is dropped and should be closed. :param conn: urllib3.connection.HTTPConnection object.

urllib3.util.is_fp_closed(obj: object) bool[source]

Checks whether a given file-like object is closed.

Parameters:

obj – The file-like object to check.

urllib3.util.make_headers(keep_alive: bool | None = None, accept_encoding: bool | list[str] | str | None = None, user_agent: str | None = None, basic_auth: str | None = None, proxy_basic_auth: str | None = None, disable_cache: bool | None = None) dict[str, str][source]

Shortcuts for generating request headers.

Parameters:
  • keep_alive – If True, adds ‘connection: keep-alive’ header.

  • accept_encoding – Can be a boolean, list, or string. True translates to ‘gzip,deflate’. If either the brotli or brotlicffi package is installed ‘gzip,deflate,br’ is used instead. 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.

  • proxy_basic_auth – Colon-separated username:password string for ‘proxy-authorization: basic …’ auth header.

  • disable_cache – If True, adds ‘cache-control: no-cache’ header.

Example:

import urllib3

print(urllib3.util.make_headers(keep_alive=True, user_agent="Batman/1.0"))
# {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
print(urllib3.util.make_headers(accept_encoding=True))
# {'accept-encoding': 'gzip,deflate'}
urllib3.util.parse_url(url: str) Url[source]

Given a url, return a parsed Url namedtuple. Best-effort is performed to parse incomplete urls. Fields not provided will be None. This parser is RFC 3986 and RFC 6874 compliant.

The parser logic and helper functions are based heavily on work done in the rfc3986 module.

Parameters:

url (str) – URL to parse into a Url namedtuple.

Partly backwards-compatible with urllib.parse.

Example:

import urllib3

print( urllib3.util.parse_url('http://google.com/mail/'))
# Url(scheme='http', host='google.com', port=None, path='/mail/', ...)

print( urllib3.util.parse_url('google.com:80'))
# Url(scheme=None, host='google.com', port=80, path=None, ...)

print( urllib3.util.parse_url('/foo?bar'))
# Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
urllib3.util.resolve_cert_reqs(candidate: None | int | str) VerifyMode[source]

Resolves the argument to a numeric constant, which can be passed to the wrap_socket function/method from the ssl module. Defaults to ssl.CERT_REQUIRED. If given a string it is assumed to be the name of the constant in the ssl module or its abbreviation. (So you can specify REQUIRED instead of CERT_REQUIRED. If it’s neither None nor a string we assume it is already the numeric constant which can directly be passed to wrap_socket.

urllib3.util.resolve_ssl_version(candidate: None | int | str) int[source]

like resolve_cert_reqs

urllib3.util.ssl_wrap_socket(sock: socket.socket, keyfile: str | None = None, certfile: str | None = None, cert_reqs: int | None = None, ca_certs: str | None = None, server_hostname: str | None = None, ssl_version: int | None = None, ciphers: str | None = None, ssl_context: ssl.SSLContext | None = None, ca_cert_dir: str | None = None, key_password: str | None = None, ca_cert_data: None | str | bytes = None, tls_in_tls: bool = False) ssl.SSLSocket | SSLTransportType[source]

All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using ssl.wrap_socket().

Parameters:
  • server_hostname – When SNI is supported, the expected hostname of the certificate

  • ssl_context – A pre-made SSLContext object. If none is provided, one will be created using create_urllib3_context().

  • ciphers – A string of ciphers we wish the client to support.

  • ca_cert_dir – A directory containing CA certificates in multiple separate files, as supported by OpenSSL’s -CApath flag or the capath argument to SSLContext.load_verify_locations().

  • key_password – Optional password if the keyfile is encrypted.

  • ca_cert_data – Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations()

  • tls_in_tls – Use SSLTransport to wrap the existing socket.

urllib3.util.wait_for_read(sock: socket, timeout: float | None = None) bool[source]

Waits for reading to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired.

urllib3.util.wait_for_write(sock: socket, timeout: float | None = None) bool[source]

Waits for writing to be available on a given socket. Returns True if the socket is readable, or False if the timeout expired.

Filepost

urllib3.filepost.choose_boundary() str[source]

Our embarrassingly-simple replacement for mimetools.choose_boundary.

urllib3.filepost.encode_multipart_formdata(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]], boundary: str | None = None) tuple[bytes, str][source]

Encode a dictionary of fields using the multipart/form-data MIME format.

Parameters:
  • fields – Dictionary of fields or list of (key, RequestField). Values are processed by urllib3.fields.RequestField.from_tuples().

  • boundary – If not specified, then a random boundary will be generated using urllib3.filepost.choose_boundary().

urllib3.filepost.iter_field_objects(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]]) Iterable[RequestField][source]

Iterate over fields.

Supports list of (k, v) tuples and dicts, and lists of RequestField.

Request

A convenience, top-level request method. It uses a module-global PoolManager instance. Therefore, its side effects could be shared across dependencies relying on it. To avoid side effects create a new PoolManager instance and use it instead. The method does not accept low-level **urlopen_kw keyword arguments.

Response

class urllib3.response.BaseHTTPResponse(*, headers: Mapping[str, str] | Mapping[bytes, bytes] | None = None, status: int, version: int, reason: str | None, decode_content: bool, request_url: str | None, retries: Retry | None = None)[source]
CONTENT_DECODERS = ['gzip', 'deflate']
DECODER_ERROR_CLASSES: tuple[type[Exception], ...] = (<class 'OSError'>, <class 'zlib.error'>)
REDIRECT_STATUSES = [301, 302, 303, 307, 308]
close() None[source]

Flush and close the IO object.

This method has no effect if the file is already closed.

property connection: HTTPConnection | None
property data: bytes
drain_conn() None[source]
get_redirect_location() str | None | Literal[False][source]

Should we redirect and where to?

Returns:

Truthy redirect location string if we got a redirect status code and valid location. None if redirect status and no location. False if not a redirect status code.

getheader(name: str, default: str | None = None) str | None[source]
getheaders() HTTPHeaderDict[source]
geturl() str | None[source]
info() HTTPHeaderDict[source]
json() Any[source]

Parses the body of the HTTP response as JSON.

To use a custom JSON decoder pass the result of HTTPResponse.data to the decoder.

This method can raise either UnicodeDecodeError or json.JSONDecodeError.

Read more here.

read(amt: int | None = None, decode_content: bool | None = None, cache_content: bool = False) bytes[source]
read_chunked(amt: int | None = None, decode_content: bool | None = None) Iterator[bytes][source]
readinto(b: bytearray) int[source]
release_conn() None[source]
property retries: Retry | None
stream(amt: int | None = 65536, decode_content: bool | None = None) Iterator[bytes][source]
property url: str | None
class urllib3.response.BytesQueueBuffer[source]

Memory-efficient bytes buffer

To return decoded data in read() and still follow the BufferedIOBase API, we need a buffer to always return the correct amount of bytes.

This buffer should be filled using calls to put()

Our maximum memory usage is determined by the sum of the size of:

  • self.buffer, which contains the full data

  • the largest chunk that we will copy in get()

The worst case scenario is a single chunk, in which case we’ll make a full copy of the data inside get().

get(n: int) bytes[source]
put(data: bytes) None[source]
class urllib3.response.ContentDecoder[source]
decompress(data: bytes) bytes[source]
flush() bytes[source]
class urllib3.response.DeflateDecoder[source]
decompress(data: bytes) bytes[source]
flush() bytes[source]
class urllib3.response.GzipDecoder[source]
decompress(data: bytes) bytes[source]
flush() bytes[source]
class urllib3.response.GzipDecoderState[source]
FIRST_MEMBER = 0
OTHER_MEMBERS = 1
SWALLOW_DATA = 2
class urllib3.response.HTTPResponse(body: _TYPE_BODY = '', headers: Mapping[str, str] | Mapping[bytes, bytes] | None = None, status: int = 0, version: int = 0, reason: str | None = None, preload_content: bool = True, decode_content: bool = True, original_response: _HttplibHTTPResponse | None = None, pool: HTTPConnectionPool | None = None, connection: HTTPConnection | None = None, msg: _HttplibHTTPMessage | None = None, retries: Retry | None = None, enforce_content_length: bool = True, request_method: str | None = None, request_url: str | None = None, auto_close: bool = True)[source]

HTTP Response container.

Backwards-compatible with http.client.HTTPResponse but the response body is loaded and decoded on-demand when the data property is accessed. This class is also compatible with the Python standard library’s io module, and can hence be treated as a readable object in the context of that framework.

Extra parameters for behaviour not present in http.client.HTTPResponse:

Parameters:
  • preload_content – If True, the response’s body will be preloaded during construction.

  • decode_content – If True, will attempt to decode the body based on the ‘content-encoding’ header.

  • original_response – When this HTTPResponse wrapper is generated from an http.client.HTTPResponse object, it’s convenient to include the original for debug purposes. It’s otherwise unused.

  • retries – The retries contains the last Retry that was used during the request.

  • enforce_content_length – Enforce content length checking. Body returned by server must match value of Content-Length header, if present. Otherwise, raise error.

close() None[source]

Flush and close the IO object.

This method has no effect if the file is already closed.

property closed: bool
property connection: HTTPConnection | None
property data: bytes
drain_conn() None[source]

Read and discard any remaining HTTP response data in the response connection.

Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.

fileno() int[source]

Returns underlying file descriptor if one exists.

OSError is raised if the IO object does not use a file descriptor.

flush() None[source]

Flush write buffers, if applicable.

This is not implemented for read-only and non-blocking streams.

isclosed() bool[source]
read(amt: int | None = None, decode_content: bool | None = None, cache_content: bool = False) bytes[source]

Similar to http.client.HTTPResponse.read(), but with two additional parameters: decode_content and cache_content.

Parameters:
  • amt – How much of the content to read. If specified, caching is skipped because it doesn’t make sense to cache partial content as the full response.

  • decode_content – If True, will attempt to decode the body based on the ‘content-encoding’ header.

  • cache_content – If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the .data property to continue working after having .read() the file object. (Overridden if amt is set.)

read_chunked(amt: int | None = None, decode_content: bool | None = None) Generator[bytes, None, None][source]

Similar to HTTPResponse.read(), but with an additional parameter: decode_content.

Parameters:
  • amt – How much of the content to read. If specified, caching is skipped because it doesn’t make sense to cache partial content as the full response.

  • decode_content – If True, will attempt to decode the body based on the ‘content-encoding’ header.

readable() bool[source]

Return whether object was opened for reading.

If False, read() will raise OSError.

release_conn() None[source]
stream(amt: int | None = 65536, decode_content: bool | None = None) Generator[bytes, None, None][source]

A generator wrapper for the read() method. A call will block until amt bytes have been read from the connection or until the connection is closed.

Parameters:
  • amt – How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned.

  • decode_content – If True, will attempt to decode the body based on the ‘content-encoding’ header.

supports_chunked_reads() bool[source]

Checks if the underlying file-like object looks like a http.client.HTTPResponse object. We do this by testing for the fp attribute. If it is present we assume it returns raw chunks as processed by read_chunked().

tell() int[source]

Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:urllib3.response.HTTPResponse.read if bytes are encoded on the wire (e.g, compressed).

property url: str | None

Returns the URL that was the source of this response. If the request that generated this response redirected, this method will return the final redirect location.

class urllib3.response.MultiDecoder(modes: str)[source]
From RFC7231:

If one or more encodings have been applied to a representation, the sender that applied the encodings MUST generate a Content-Encoding header field that lists the content codings in the order in which they were applied.

decompress(data: bytes) bytes[source]
flush() bytes[source]