desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Dict-like keys() that returns a list of names of cookies from the
jar. See values() and items().'
| def keys(self):
| return list(self.iterkeys())
|
'Dict-like itervalues() that returns an iterator of values of cookies
from the jar. See iterkeys() and iteritems().'
| def itervalues(self):
| for cookie in iter(self):
(yield cookie.value)
|
'Dict-like values() that returns a list of values of cookies from the
jar. See keys() and items().'
| def values(self):
| return list(self.itervalues())
|
'Dict-like iteritems() that returns an iterator of name-value tuples
from the jar. See iterkeys() and itervalues().'
| def iteritems(self):
| for cookie in iter(self):
(yield (cookie.name, cookie.value))
|
'Dict-like items() that returns a list of name-value tuples from the
jar. See keys() and values(). Allows client-code to call
``dict(RequestsCookieJar)`` and get a vanilla python dict of key value
pairs.'
| def items(self):
| return list(self.iteritems())
|
'Utility method to list all the domains in the jar.'
| def list_domains(self):
| domains = []
for cookie in iter(self):
if (cookie.domain not in domains):
domains.append(cookie.domain)
return domains
|
'Utility method to list all the paths in the jar.'
| def list_paths(self):
| paths = []
for cookie in iter(self):
if (cookie.path not in paths):
paths.append(cookie.path)
return paths
|
'Returns True if there are multiple domains in the jar.
Returns False otherwise.'
| def multiple_domains(self):
| domains = []
for cookie in iter(self):
if ((cookie.domain is not None) and (cookie.domain in domains)):
return True
domains.append(cookie.domain)
return False
|
'Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.'
| def get_dict(self, domain=None, path=None):
| dictionary = {}
for cookie in iter(self):
if (((domain is None) or (cookie.domain == domain)) and ((path is None) or (cookie.path == path))):
dictionary[cookie.name] = cookie.value
return dictionary
|
'Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).'
| def __getitem__(self, name):
| return self._find_no_duplicates(name)
|
'Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.'
| def __setitem__(self, name, value):
| self.set(name, value)
|
'Deletes a cookie given a name. Wraps ``cookielib.CookieJar``\'s
``remove_cookie_by_name()``.'
| def __delitem__(self, name):
| remove_cookie_by_name(self, name)
|
'Updates this jar with cookies from another CookieJar or dict-like'
| def update(self, other):
| if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
|
'Requests uses this method internally to get cookie values. Takes as
args name and optional domain and path. Returns a cookie.value. If
there are conflicting cookies, _find arbitrarily chooses one. See
_find_no_duplicates if you want an exception thrown if there are
conflicting cookies.'
| def _find(self, name, domain=None, path=None):
| for cookie in iter(self):
if (cookie.name == name):
if ((domain is None) or (cookie.domain == domain)):
if ((path is None) or (cookie.path == path)):
return cookie.value
raise KeyError(('name=%r, domain=%r, path=%r' % (name, domain, path)))
|
'Both ``__get_item__`` and ``get`` call this function: it\'s never
used elsewhere in Requests. Takes as args name and optional domain and
path. Returns a cookie.value. Throws KeyError if cookie is not found
and CookieConflictError if there are multiple cookies that match name
and optionally domain and path.'
| def _find_no_duplicates(self, name, domain=None, path=None):
| toReturn = None
for cookie in iter(self):
if (cookie.name == name):
if ((domain is None) or (cookie.domain == domain)):
if ((path is None) or (cookie.path == path)):
if (toReturn is not None):
raise CookieConflictError(('There ar... |
'Unlike a normal CookieJar, this class is pickleable.'
| def __getstate__(self):
| state = self.__dict__.copy()
state.pop('_cookies_lock')
return state
|
'Unlike a normal CookieJar, this class is pickleable.'
| def __setstate__(self, state):
| self.__dict__.update(state)
if ('_cookies_lock' not in self.__dict__):
self._cookies_lock = threading.RLock()
|
'Return a copy of this RequestsCookieJar.'
| def copy(self):
| new_cj = RequestsCookieJar()
new_cj.update(self)
return new_cj
|
'reset analyser, clear any state'
| def reset(self):
| self._mDone = False
self._mTotalChars = 0
self._mFreqChars = 0
|
'feed a character with known length'
| def feed(self, aBuf, aCharLen):
| if (aCharLen == 2):
order = self.get_order(aBuf)
else:
order = (-1)
if (order >= 0):
self._mTotalChars += 1
if (order < self._mTableSize):
if (512 > self._mCharToFreqOrder[order]):
self._mFreqChars += 1
|
'return confidence based on existing data'
| def get_confidence(self):
| if ((self._mTotalChars <= 0) or (self._mFreqChars <= MINIMUM_DATA_THRESHOLD)):
return SURE_NO
if (self._mTotalChars != self._mFreqChars):
r = (self._mFreqChars / ((self._mTotalChars - self._mFreqChars) * self._mTypicalDistributionRatio))
if (r < SURE_YES):
return r
return... |
'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.'
| def get_redirect_location(self):
| if (self.status in self.REDIRECT_STATUSES):
return self.headers.get('location')
return False
|
'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-up the _decoder attribute if necessar.'
| 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... |
'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
try:
try:
if (amt is None):
data = self._fp.read()
flush_decoder = True
else:
... |
'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:
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:
(yield data)
|
'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... |
'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 (self._original_response and (self._original_response._method.upper() == 'HEAD')):
self._original_response.close()
... |
'Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for customization.'
| def _new_pool(self, scheme, host, port):
| pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if (scheme == 'http'):
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
kwargs.pop(kw, None)
return pool_cls(host, port, **kwargs)
|
'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``.'
| def connection_from_host(self, host, port=None, scheme='http'):
| if (not host):
raise LocationValueError('No host specified.')
scheme = (scheme or 'http')
port = (port or port_by_scheme.get(scheme, 80))
pool_key = (scheme, host, port)
with self.pools.lock:
pool = self.pools.get(pool_key)
if pool:
return pool
pool ... |
'Similar to :func:`urllib3.connectionpool.connection_from_url` but
doesn\'t pass any additional parameters to the
:class:`urllib3.connectionpool.ConnectionPool` constructor.
Additional parameters are taken from the :class:`.PoolManager`
constructor.'
| def connection_from_url(self, url):
| u = parse_url(url)
return self.connection_from_host(u.host, port=u.port, scheme=u.scheme)
|
'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)
|
'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:
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 = _dict_setdefault(self, key_lower, new_vals)
if (new_vals is not vals):
if isinstance(vals, list):
vals.append(val)
else:
_dict_setitem(self, key_lower, [vals[0], vals[1], 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 ({} 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 = _dict_getitem(self, key.lower())
except KeyError:
return []
else:
if isinstance(vals, tuple):
return [vals[1]]
else:
return vals[1:]
|
'Iterate over all header lines, including duplicate ones.'
| def iteritems(self):
| for key in self:
vals = _dict_getitem(self, key)
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 = _dict_getitem(self, key)
(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:
... |
'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 the type is not an integer or a float, or if i... | @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
try:
float(value)
except (TypeError, ValueError):
raise ValueError(('Timeout value %s was %s, but it must be an int or ... |
'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' % (retrie... |
'Formula for computing the current backoff
:rtype: float'
| def get_backoff_time(self):
| if (self._observed_errors <= 1):
return 0
backoff_value = (self.backoff_factor * (2 ** (self._observed_errors - 1)))
return min(self.BACKOFF_MAX, backoff_value)
|
'Sleep between retry attempts using an exponential backoff.
By default, the backoff factor is 0 and this method will return
immediately.'
| def sleep(self):
| backoff = self.get_backoff_time()
if (backoff <= 0):
return
time.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))
|
'Is this method/status code retryable? (Based on method/codes whitelists)'
| def is_forced_retry(self, method, status_code):
| if (self.method_whitelist and (method.upper() not in self.method_whitelist)):
return False
return (self.status_forcelist and (status_code in self.status_forcelist))
|
'Are we out of retries?'
| def is_exhausted(self):
| retry_counts = (self.total, self.connect, self.read, self.redirect)
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
_observed_errors = self._observed_errors
connect = self.connect
read = self.read
redirect = self.redirect
cause = 'unknown'
i... |
'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():
| pass
|
'Return a fresh :class:`HTTPConnection`.'
| def _new_conn(self):
| self.num_connections += 1
log.info(('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 Empty:
if self.block:
raise EmptyPoolError(self, 'Pool reached maximum size and no more con... |
'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 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, **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)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.