desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed).'
def tell(self):
return self._fp_bytes_read
'Set initial length value for Response content if available.'
def _init_length(self, request_method):
length = self.headers.get('content-length') if ((length is not None) and self.chunked): log.warning('Received response with both Content-Length and Transfer-Encoding set. This is expressly forbidden by RFC 7230 sec 3.3.2. Ignoring Content-Length a...
'Set-up the _decoder attribute if necessary.'
def _init_decoder(self):
content_encoding = self.headers.get('content-encoding', '').lower() if ((self._decoder is None) and (content_encoding in self.CONTENT_DECODERS)): self._decoder = _get_decoder(content_encoding)
'Decode the data passed in and potentially flush the decoder.'
def _decode(self, data, decode_content, flush_decoder):
try: if (decode_content and self._decoder): data = self._decoder.decompress(data) except (IOError, zlib.error) as e: content_encoding = self.headers.get('content-encoding', '').lower() raise DecodeError(('Received response with content-encoding: %s, but fail...
'Flushes the decoder. Should only be called if the decoder is actually being used.'
def _flush_decoder(self):
if self._decoder: buf = self._decoder.decompress('') return (buf + self._decoder.flush()) return ''
'Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool.'
@contextmanager def _error_catcher(self):
clean_exit = False try: try: (yield) except SocketTimeout: raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: if ('read operation timed out' not in str(e)): raise raise ReadT...
'Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param 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. :param decode_content: If True, will at...
def read(self, amt=None, decode_content=None, cache_content=False):
self._init_decoder() if (decode_content is None): decode_content = self.decode_content if (self._fp is None): return flush_decoder = False data = None with self._error_catcher(): if (amt is None): data = self._fp.read() flush_decoder = True ...
'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. :param 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 compre...
def stream(self, amt=(2 ** 16), decode_content=None):
if (self.chunked and self.supports_chunked_reads()): for line in self.read_chunked(amt, decode_content=decode_content): (yield line) else: while (not is_fp_closed(self._fp)): data = self.read(amt=amt, decode_content=decode_content) if data: (yi...
'Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``.'
@classmethod def from_httplib(ResponseCls, r, **response_kw):
headers = r.msg if (not isinstance(headers, HTTPHeaderDict)): if PY3: headers = HTTPHeaderDict(headers.items()) else: headers = HTTPHeaderDict.from_httplib(headers) strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, versi...
'Checks if the underlying file-like object looks like a httplib.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().'
def supports_chunked_reads(self):
return hasattr(self._fp, 'fp')
'Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param decode_content: If True, will attempt to decode the body based on the \'content-encoding\' header.'
def read_chunked(self, amt=None, decode_content=None):
self._init_decoder() if (not self.chunked): raise ResponseNotChunked("Response is not chunked. Header 'transfer-encoding: chunked' is missing.") if (not self.supports_chunked_reads()): raise BodyNotHttplibCompatible('Body should be httplib.HTTPResponse lik...
'Create a new :class:`ConnectionPool` based on host, port, scheme, and any additional pool keyword arguments. If ``request_context`` is provided, it is provided as keyword arguments to the pool class used. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companio...
def _new_pool(self, scheme, host, port, request_context=None):
pool_cls = self.pool_classes_by_scheme[scheme] if (request_context is None): request_context = self.connection_pool_kw.copy() for key in ('scheme', 'host', 'port'): request_context.pop(key, None) if (scheme == 'http'): for kw in SSL_KEYWORDS: request_context.pop(kw, N...
'Empty our store of pools and direct them all to close. This will not affect in-flight connections, but they will not be re-used after completion.'
def clear(self):
self.pools.clear()
'Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn\'t given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is provided, it is merged with the instance\'s ``connection_pool_kw`` variable and used to create the new connection po...
def connection_from_host(self, host, port=None, scheme='http', pool_kwargs=None):
if (not host): raise LocationValueError('No host specified.') request_context = self._merge_pool_kwargs(pool_kwargs) request_context['scheme'] = (scheme or 'http') if (not port): port = port_by_scheme.get(request_context['scheme'].lower(), 80) request_context['port'] = port ...
'Get a :class:`ConnectionPool` based on the request context. ``request_context`` must at least contain the ``scheme`` key and its value must be a key in ``key_fn_by_scheme`` instance variable.'
def connection_from_context(self, request_context):
scheme = request_context['scheme'].lower() pool_key_constructor = self.key_fn_by_scheme[scheme] pool_key = pool_key_constructor(request_context) return self.connection_from_pool_key(pool_key, request_context=request_context)
'Get a :class:`ConnectionPool` based on the provided pool key. ``pool_key`` should be a namedtuple that only contains immutable objects. At a minimum it must have the ``scheme``, ``host``, and ``port`` fields.'
def connection_from_pool_key(self, pool_key, request_context=None):
with self.pools.lock: pool = self.pools.get(pool_key) if pool: return pool scheme = request_context['scheme'] host = request_context['host'] port = request_context['port'] pool = self._new_pool(scheme, host, port, request_context=request_context) s...
'Similar to :func:`urllib3.connectionpool.connection_from_url`. If ``pool_kwargs`` is not provided and a new pool needs to be constructed, ``self.connection_pool_kw`` is used to initialize the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs`` is provided, it is used instead. Note that if a new pool doe...
def connection_from_url(self, url, pool_kwargs=None):
u = parse_url(url) return self.connection_from_host(u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs)
'Merge a dictionary of override values for self.connection_pool_kw. This does not modify self.connection_pool_kw and returns a new dict. Any keys in the override dictionary with a value of ``None`` are removed from the merged dictionary.'
def _merge_pool_kwargs(self, override):
base_pool_kwargs = self.connection_pool_kw.copy() if override: for (key, value) in override.items(): if (value is None): try: del base_pool_kwargs[key] except KeyError: pass else: base_pool_kw...
'Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen` with custom cross-host redirect logic and only sends the request-uri portion of the ``url``. The given ``url`` parameter must be absolute, such that an appropriate :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.'
def urlopen(self, method, url, redirect=True, **kw):
u = parse_url(url) conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme) kw['assert_same_host'] = False kw['redirect'] = False if ('headers' not in kw): kw['headers'] = self.headers if ((self.proxy is not None) and (u.scheme == 'http')): response = conn.urlopen(m...
'Sets headers needed by proxies: specifically, the Accept and Host headers. Only sets headers not provided by the user.'
def _set_proxy_headers(self, url, headers=None):
headers_ = {'Accept': '*/*'} netloc = parse_url(url).netloc if netloc: headers_['Host'] = netloc if headers: headers_.update(headers) return headers_
'Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.'
def urlopen(self, method, url, redirect=True, **kw):
u = parse_url(url) if (u.scheme == 'http'): headers = kw.get('headers', self.headers) kw['headers'] = self._set_proxy_headers(url, headers) return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)
'Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)'
def is_package(self, fullname):
return hasattr(self.__get_module(fullname), '__path__')
'Return None Required, if is_package is implemented'
def get_code(self, fullname):
self.__get_module(fullname) return None
'Initialize an ordered dictionary. Signature is the same as for regular dictionaries, but keyword arguments are not recommended because their insertion order is arbitrary.'
def __init__(self, *args, **kwds):
if (len(args) > 1): raise TypeError(('expected at most 1 arguments, got %d' % len(args))) try: self.__root except AttributeError: self.__root = root = [] root[:] = [root, root, None] self.__map = {} self.__update(*args, **kwds)
'od.__setitem__(i, y) <==> od[i]=y'
def __setitem__(self, key, value, dict_setitem=dict.__setitem__):
if (key not in self): root = self.__root last = root[0] last[1] = root[0] = self.__map[key] = [last, root, key] dict_setitem(self, key, value)
'od.__delitem__(y) <==> del od[y]'
def __delitem__(self, key, dict_delitem=dict.__delitem__):
dict_delitem(self, key) (link_prev, link_next, key) = self.__map.pop(key) link_prev[1] = link_next link_next[0] = link_prev
'od.__iter__() <==> iter(od)'
def __iter__(self):
root = self.__root curr = root[1] while (curr is not root): (yield curr[2]) curr = curr[1]
'od.__reversed__() <==> reversed(od)'
def __reversed__(self):
root = self.__root curr = root[0] while (curr is not root): (yield curr[2]) curr = curr[0]
'od.clear() -> None. Remove all items from od.'
def clear(self):
try: for node in self.__map.itervalues(): del node[:] root = self.__root root[:] = [root, root, None] self.__map.clear() except AttributeError: pass dict.clear(self)
'od.popitem() -> (k, v), return and remove a (key, value) pair. Pairs are returned in LIFO order if last is true or FIFO order if false.'
def popitem(self, last=True):
if (not self): raise KeyError('dictionary is empty') root = self.__root if last: link = root[0] link_prev = link[0] link_prev[1] = root root[0] = link_prev else: link = root[1] link_next = link[1] root[1] = link_next link_next...
'od.keys() -> list of keys in od'
def keys(self):
return list(self)
'od.values() -> list of values in od'
def values(self):
return [self[key] for key in self]
'od.items() -> list of (key, value) pairs in od'
def items(self):
return [(key, self[key]) for key in self]
'od.iterkeys() -> an iterator over the keys in od'
def iterkeys(self):
return iter(self)
'od.itervalues -> an iterator over the values in od'
def itervalues(self):
for k in self: (yield self[k])
'od.iteritems -> an iterator over the (key, value) items in od'
def iteritems(self):
for k in self: (yield (k, self[k]))
'od.update(E, **F) -> None. Update od from dict/iterable E and F. If E is a dict instance, does: for k in E: od[k] = E[k] If E has a .keys() method, does: for k in E.keys(): od[k] = E[k] Or if E is an iterable of items, does: for k, v in E: od[k] = v In either case, this is followed by: for k, ...
def update(*args, **kwds):
if (len(args) > 2): raise TypeError(('update() takes at most 2 positional arguments (%d given)' % (len(args),))) elif (not args): raise TypeError('update() takes at least 1 argument (0 given)') self = args[0] other = () if (len(args) == 2)...
'od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.'
def pop(self, key, default=__marker):
if (key in self): result = self[key] del self[key] return result if (default is self.__marker): raise KeyError(key) return default
'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'
def setdefault(self, key, default=None):
if (key in self): return self[key] self[key] = default return default
'od.__repr__() <==> repr(od)'
def __repr__(self, _repr_running={}):
call_key = (id(self), _get_ident()) if (call_key in _repr_running): return '...' _repr_running[call_key] = 1 try: if (not self): return ('%s()' % (self.__class__.__name__,)) return ('%s(%r)' % (self.__class__.__name__, self.items())) finally: del _repr_run...
'Return state information for pickling'
def __reduce__(self):
items = [[k, self[k]] for k in self] inst_dict = vars(self).copy() for k in vars(OrderedDict()): inst_dict.pop(k, None) if inst_dict: return (self.__class__, (items,), inst_dict) return (self.__class__, (items,))
'od.copy() -> a shallow copy of od'
def copy(self):
return self.__class__(self)
'OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S and values equal to v (which defaults to None).'
@classmethod def fromkeys(cls, iterable, value=None):
d = cls() for key in iterable: d[key] = value return d
'od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive while comparison to a regular mapping is order-insensitive.'
def __eq__(self, other):
if isinstance(other, OrderedDict): return ((len(self) == len(other)) and (self.items() == other.items())) return dict.__eq__(self, other)
'od.viewkeys() -> a set-like object providing a view on od\'s keys'
def viewkeys(self):
return KeysView(self)
'od.viewvalues() -> an object providing a view on od\'s values'
def viewvalues(self):
return ValuesView(self)
'od.viewitems() -> a set-like object providing a view on od\'s items'
def viewitems(self):
return ItemsView(self)
'A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters. Supports constructing :class:`~urllib3.fields.RequestField` from 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:: \'foo\': \'bar\', \'fakef...
@classmethod def from_tuples(cls, fieldname, value):
if isinstance(value, tuple): if (len(value) == 3): (filename, data, content_type) = value else: (filename, data) = value content_type = guess_content_type(filename) else: filename = None content_type = None data = value request_para...
'Overridable helper function to format a single header parameter. :param name: The name of the parameter, a string expected to be ASCII only. :param value: The value of the parameter, provided as a unicode string.'
def _render_part(self, name, value):
return format_header_param(name, value)
'Helper function to format and quote a single header. Useful for single headers that are composed of multiple items. E.g., \'Content-Disposition\' fields. :param header_parts: A sequence of (k, v) typles or a :class:`dict` of (k, v) to format as `k1="v1"; k2="v2"; ...`.'
def _render_parts(self, header_parts):
parts = [] iterable = header_parts if isinstance(header_parts, dict): iterable = header_parts.items() for (name, value) in iterable: if (value is not None): parts.append(self._render_part(name, value)) return '; '.join(parts)
'Renders the headers for this request field.'
def render_headers(self):
lines = [] sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location'] for sort_key in sort_keys: if self.headers.get(sort_key, False): lines.append(('%s: %s' % (sort_key, self.headers[sort_key]))) for (header_name, header_value) in self.headers.items(): if (he...
'Makes this request field into a multipart request field. This method overrides "Content-Disposition", "Content-Type" and "Content-Location" headers to the request parameter. :param content_type: The \'Content-Type\' of the request body. :param content_location: The \'Content-Location\' of the request body.'
def make_multipart(self, content_disposition=None, content_type=None, content_location=None):
self.headers['Content-Disposition'] = (content_disposition or 'form-data') self.headers['Content-Disposition'] += '; '.join(['', self._render_parts((('name', self._name), ('filename', self._filename)))]) self.headers['Content-Type'] = content_type self.headers['Content-Location'] = content_location
'D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.'
def pop(self, key, default=__marker):
try: value = self[key] except KeyError: if (default is self.__marker): raise return default else: del self[key] return value
'Adds a (name, value) pair, doesn\'t overwrite the value if it already exists. >>> headers = HTTPHeaderDict(foo=\'bar\') >>> headers.add(\'Foo\', \'baz\') >>> headers[\'foo\'] \'bar, baz\''
def add(self, key, val):
key_lower = key.lower() new_vals = [key, val] vals = self._container.setdefault(key_lower, new_vals) if (new_vals is not vals): vals.append(val)
'Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__'
def extend(self, *args, **kwargs):
if (len(args) > 1): raise TypeError('extend() takes at most 1 positional arguments ({0} given)'.format(len(args))) other = (args[0] if (len(args) >= 1) else ()) if isinstance(other, HTTPHeaderDict): for (key, val) in other.iteritems(): self.add(key, val) ...
'Returns a list of all the values for the named field. Returns an empty list if the key doesn\'t exist.'
def getlist(self, key):
try: vals = self._container[key.lower()] except KeyError: return [] else: return vals[1:]
'Iterate over all header lines, including duplicate ones.'
def iteritems(self):
for key in self: vals = self._container[key.lower()] for val in vals[1:]: (yield (vals[0], val))
'Iterate over all headers, merging duplicate ones together.'
def itermerged(self):
for key in self: val = self._container[key.lower()] (yield (val[0], ', '.join(val[1:])))
'Read headers from a Python 2 httplib message object.'
@classmethod def from_httplib(cls, message):
headers = [] for line in message.headers: if line.startswith((' ', ' DCTB ')): (key, value) = headers[(-1)] headers[(-1)] = (key, ((value + '\r\n') + line.rstrip())) continue (key, value) = line.split(':', 1) headers.append((key, value.strip())) ...
'Establish a socket connection and set nodelay settings on it. :return: New socket connection.'
def _new_conn(self):
extra_kw = {} if self.source_address: extra_kw['source_address'] = self.source_address if self.socket_options: extra_kw['socket_options'] = self.socket_options try: conn = connection.create_connection((self.host, self.port), self.timeout, **extra_kw) except SocketTimeout as e...
'Alternative to the common request method, which sends the body with chunked encoding and not as one block'
def request_chunked(self, method, url, body=None, headers=None):
headers = HTTPHeaderDict((headers if (headers is not None) else {})) skip_accept_encoding = ('accept-encoding' in headers) skip_host = ('host' in headers) self.putrequest(method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host) for (header, value) in headers.items(): self...
'This method should only be called once, before the connection is used.'
def set_cert(self, key_file=None, cert_file=None, cert_reqs=None, ca_certs=None, assert_hostname=None, assert_fingerprint=None, ca_cert_dir=None):
if (cert_reqs is None): if (ca_certs or ca_cert_dir): cert_reqs = 'CERT_REQUIRED' elif (self.ssl_context is not None): cert_reqs = self.ssl_context.verify_mode self.key_file = key_file self.cert_file = cert_file self.cert_reqs = cert_reqs self.assert_hostname ...
'Return a file descriptor from a file object. This wraps _fileobj_to_fd() to do an exhaustive search in case the object is invalid but we still have it in our map. Used by unregister() so we can unregister an object that was previously registered even if it is closed. It is also used by _SelectorMapping'
def _fileobj_lookup(self, fileobj):
try: return _fileobj_to_fd(fileobj) except ValueError: for key in self._fd_to_key.values(): if (key.fileobj is fileobj): return key.fd raise
'Register a file object for a set of events to monitor.'
def register(self, fileobj, events, data=None):
if ((not events) or (events & (~ (EVENT_READ | EVENT_WRITE)))): raise ValueError('Invalid events: {0!r}'.format(events)) key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data) if (key.fd in self._fd_to_key): raise KeyError('{0!r} (FD {1}) is already regi...
'Unregister a file object from being monitored.'
def unregister(self, fileobj):
try: key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) except KeyError: raise KeyError('{0!r} is not registered'.format(fileobj)) except socket.error as e: if (e.errno != errno.EBADF): raise else: for key in self._fd_to_key.values(): ...
'Change a registered file object monitored events and data.'
def modify(self, fileobj, events, data=None):
try: key = self._fd_to_key[self._fileobj_lookup(fileobj)] except KeyError: raise KeyError('{0!r} is not registered'.format(fileobj)) if (events != key.events): self.unregister(fileobj) key = self.register(fileobj, events, data) elif (data != key.data): ke...
'Perform the actual selection until some monitored file objects are ready or the timeout expires.'
def select(self, timeout=None):
raise NotImplementedError()
'Close the selector. This must be called to ensure that all underlying resources are freed.'
def close(self):
self._fd_to_key.clear() self._map = None
'Return the key associated with a registered file object.'
def get_key(self, fileobj):
mapping = self.get_map() if (mapping is None): raise RuntimeError('Selector is closed') try: return mapping[fileobj] except KeyError: raise KeyError('{0!r} is not registered'.format(fileobj))
'Return a mapping of file objects to selector keys'
def get_map(self):
return self._map
'Return the key associated to a given file descriptor Return None if it is not found.'
def _key_from_fd(self, fd):
try: return self._fd_to_key[fd] except KeyError: return None
'Check that a timeout attribute is valid. :param value: The timeout value to validate :param name: The name of the timeout attribute to validate. This is used to specify in error messages. :return: The validated and casted version of the given value. :raises ValueError: If it is a numeric value less than or equal to ze...
@classmethod def _validate_timeout(cls, value, name):
if (value is _Default): return cls.DEFAULT_TIMEOUT if ((value is None) or (value is cls.DEFAULT_TIMEOUT)): return value if isinstance(value, bool): raise ValueError('Timeout cannot be a boolean value. It must be an int, float or None.') try:...
'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 :class:`Timeout` object that sets the individual timeouts to the ``timeout`` value passed to this function. :param timeout: The legacy timeout value....
@classmethod def from_float(cls, timeout):
return Timeout(read=timeout, connect=timeout)
'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. :return: a copy of the timeout object :rtype: :class:`Timeout`'
def clone(self):
return Timeout(connect=self._connect, read=self._read, total=self.total)
'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.'
def start_connect(self):
if (self._start_connect is not None): raise TimeoutStateError('Timeout timer has already been started.') self._start_connect = current_time() return self._start_connect
'Gets the time elapsed since the call to :meth:`start_connect`. :return: Elapsed time. :rtype: float :raises urllib3.exceptions.TimeoutStateError: if you attempt to get duration for a timer that hasn\'t been started.'
def get_connect_duration(self):
if (self._start_connect is None): raise TimeoutStateError("Can't get connect duration for timer that has not started.") return (current_time() - self._start_connect)
'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. :return: Connect timeout. :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None'
@property def connect_timeout(self):
if (self.total is None): return self._connect if ((self._connect is None) or (self._connect is self.DEFAULT_TIMEOUT)): return self.total return min(self._connect, self.total)
'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 :exc:`~urllib3.excepti...
@property def read_timeout(self):
if ((self.total is not None) and (self.total is not self.DEFAULT_TIMEOUT) and (self._read is not None) and (self._read is not self.DEFAULT_TIMEOUT)): if (self._start_connect is None): return self._read return max(0, min((self.total - self.get_connect_duration()), self._read)) elif ((...
'Backwards-compatibility for the old retries format.'
@classmethod def from_int(cls, retries, redirect=True, default=None):
if (retries is None): retries = (default if (default is not None) else cls.DEFAULT) if isinstance(retries, Retry): return retries redirect = (bool(redirect) and None) new_retries = cls(retries, redirect=redirect) log.debug('Converted retries value: %r -> %r', retries, ...
'Formula for computing the current backoff :rtype: float'
def get_backoff_time(self):
consecutive_errors_len = len(list(takewhile((lambda x: (x.redirect_location is None)), reversed(self.history)))) if (consecutive_errors_len <= 1): return 0 backoff_value = (self.backoff_factor * (2 ** (consecutive_errors_len - 1))) return min(self.BACKOFF_MAX, backoff_value)
'Get the value of Retry-After in seconds.'
def get_retry_after(self, response):
retry_after = response.getheader('Retry-After') if (retry_after is None): return None return self.parse_retry_after(retry_after)
'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.'
def sleep(self, response=None):
if response: slept = self.sleep_for_retry(response) if slept: return self._sleep_backoff()
'Errors when we\'re fairly sure that the server did not receive the request, so it should be safe to retry.'
def _is_connection_error(self, err):
return isinstance(err, ConnectTimeoutError)
'Errors that occur after the request has been started, so we should assume that the server began processing it.'
def _is_read_error(self, err):
return isinstance(err, (ReadTimeoutError, ProtocolError))
'Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist.'
def _is_method_retryable(self, method):
if (self.method_whitelist and (method.upper() not in self.method_whitelist)): return False return True
'Is this method/status code retryable? (Based on whitelists 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 aforeme...
def is_retry(self, method, status_code, has_retry_after=False):
if (not self._is_method_retryable(method)): return False if (self.status_forcelist and (status_code in self.status_forcelist)): return True return (self.total and self.respect_retry_after_header and has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES))
'Are we out of retries?'
def is_exhausted(self):
retry_counts = (self.total, self.connect, self.read, self.redirect, self.status) retry_counts = list(filter(None, retry_counts)) if (not retry_counts): return False return (min(retry_counts) < 0)
'Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or None if the response was received successfully. :r...
def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None):
if ((self.total is False) and error): raise six.reraise(type(error), error, _stacktrace) total = self.total if (total is not None): total -= 1 connect = self.connect read = self.read redirect = self.redirect status_count = self.status cause = 'unknown' status = None ...
'For backwards-compatibility with urlparse. We\'re nice like that.'
@property def hostname(self):
return self.host
'Absolute path including the query string.'
@property def request_uri(self):
uri = (self.path or '/') if (self.query is not None): uri += ('?' + self.query) return uri
'Network location including host and port'
@property def netloc(self):
if self.port: return ('%s:%d' % (self.host, self.port)) return self.host
'Convert self into a url This function should more or less round-trip with :func:`.parse_url`. The returned url may not be exactly the same as the url inputted to :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls with a blank port will have : removed). Example: :: >>> U = parse_url(\'http://google....
@property def url(self):
(scheme, auth, host, port, path, query, fragment) = self url = '' if (scheme is not None): url += (scheme + '://') if (auth is not None): url += (auth + '@') if (host is not None): url += host if (port is not None): url += (':' + str(port)) if (path is not Non...
'Close all pooled connections and disable the pool.'
def close(self):
pass
'Return a fresh :class:`HTTPConnection`.'
def _new_conn(self):
self.num_connections += 1 log.debug('Starting new HTTP connection (%d): %s', self.num_connections, self.host) conn = self.ConnectionCls(host=self.host, port=self.port, timeout=self.timeout.connect_timeout, strict=self.strict, **self.conn_kw) return conn
'Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is...
def _get_conn(self, timeout=None):
conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: raise ClosedPoolError(self, 'Pool is closed.') except queue.Empty: if self.block: raise EmptyPoolError(self, 'Pool reached maximum size and no more ...
'Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be inc...
def _put_conn(self, conn):
try: self.pool.put(conn, block=False) return except AttributeError: pass except queue.Full: log.warning('Connection pool is full, discarding connection: %s', self.host) if conn: conn.close()
'Called right before a request is made, after the socket is created.'
def _validate_conn(self, conn):
pass
'Helper that always returns a :class:`urllib3.util.Timeout`'
def _get_timeout(self, timeout):
if (timeout is _Default): return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: return Timeout.from_float(timeout)
'Is the error actually a timeout? Will raise a ReadTimeout or pass'
def _raise_timeout(self, err, url, timeout_value):
if isinstance(err, SocketTimeout): raise ReadTimeoutError(self, url, ('Read timed out. (read timeout=%s)' % timeout_value)) if (hasattr(err, 'errno') and (err.errno in _blocking_errnos)): raise ReadTimeoutError(self, url, ('Read timed out. (read timeout=%s)' % timeout_val...
'Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instan...
def _make_request(self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw):
self.num_requests += 1 timeout_obj = self._get_timeout(timeout) timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout try: self._validate_conn(conn) except (SocketTimeout, BaseSSLError) as e: self._raise_timeout(err=e, url=url, timeout_value=conn.timeout) ...