desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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\', \'fak...
@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
'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, value):
self._data.setdefault(key.lower(), []).append((key, value))
'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):
return (self[key].split(', ') if (key in self) else [])
'Establish a socket connection and set nodelay settings on it. :return: a new socket connection'
def _new_conn(self):
extra_args = [] if self.source_address: extra_args.append(self.source_address) conn = socket.create_connection((self.host, self.port), self.timeout, *extra_args) conn.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, self.tcp_nodelay) return conn
'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 for clear error messages :return: the value :raises ValueError: if the type is not an integer or a float, or if it is a numeric value less than zero'
@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: the 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: the 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 ((...
'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
'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) if (self.proxy is not None): conn.t...
'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()
'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)
'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) try: timeout_obj.start_connect() conn.timeout = timeout_obj.connect_timeout conn.request(method, url, **httplib_request_kw) except SocketTimeout: raise ConnectTimeoutError(self, ('Connection to %s ti...
'Close all pooled connections and disable the pool.'
def close(self):
(old_pool, self.pool) = (self.pool, None) try: while True: conn = old_pool.get(block=False) if conn: conn.close() except Empty: pass
'Check if the given ``url`` is a member of the same host as this connection pool.'
def is_same_host(self, url):
if url.startswith('/'): return True (scheme, host, port) = get_host(url) if (self.port and (not port)): port = port_by_scheme.get(scheme) elif ((not self.port) and (port == port_by_scheme.get(scheme))): port = None return ((scheme, host, port) == (self.scheme, self.host, self...
'Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you\'ll need to specify all the raw details. .. note:: More commonly, it\'s appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` ...
def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw):
if (headers is None): headers = self.headers if ((retries < 0) and (retries is not False)): raise MaxRetryError(self, url) if (release_conn is None): release_conn = response_kw.get('preload_content', True) if (assert_same_host and (not self.is_same_host(url))): raise Host...
'Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used.'
def _prepare_conn(self, conn):
if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert(key_file=self.key_file, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ca_certs=self.ca_certs, assert_hostname=self.assert_hostname, assert_fingerprint=self.assert_fingerprint) conn.ssl_version = self.ssl_version conn.conn_kw =...
'Return a fresh :class:`httplib.HTTPSConnection`.'
def _new_conn(self):
self.num_connections += 1 log.info(('Starting new HTTPS connection (%d): %s' % (self.num_connections, self.host))) if ((not self.ConnectionCls) or (self.ConnectionCls is DummyConnection)): raise SSLError("Can't connect to HTTPS URL because the SSL module is ...
'authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\username format. pw is the password for the user.'
def __init__(self, user, pw, authurl, *args, **kwargs):
super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split('\\', 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw
'Make a request using :meth:`urlopen` with the appropriate encoding of ``fields`` based on the ``method`` used. This is a convenience method that requires the least amount of manual effort. It can be used in most situations, while still having the option to drop down to more specific methods when necessary, such as :me...
def request(self, method, url, fields=None, headers=None, **urlopen_kw):
method = method.upper() if (method in self._encode_url_methods): return self.request_encode_url(method, url, fields=fields, headers=headers, **urlopen_kw) else: return self.request_encode_body(method, url, fields=fields, headers=headers, **urlopen_kw)
'Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.'
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
if fields: url += ('?' + urlencode(fields)) return self.urlopen(method, url, **urlopen_kw)
'Make a request using :meth:`urlopen` with the ``fields`` encoded in the body. This is useful for request methods like POST, PUT, PATCH, etc. When ``encode_multipart=True`` (default), then :meth:`urllib3.filepost.encode_multipart_formdata` is used to encode the payload with the appropriate content type. Otherwise :meth...
def request_encode_body(self, method, url, fields=None, headers=None, encode_multipart=True, multipart_boundary=None, **urlopen_kw):
if encode_multipart: (body, content_type) = encode_multipart_formdata((fields or {}), boundary=multipart_boundary) else: (body, content_type) = (urlencode((fields or {})), 'application/x-www-form-urlencoded') if (headers is None): headers = self.headers headers_ = {'Content-Type'...
'Initialize RequestException with `request` and `response` objects.'
def __init__(self, *args, **kwargs):
response = kwargs.pop('response', None) self.response = response self.request = kwargs.pop('request', None) if ((response is not None) and (not self.request) and hasattr(response, 'request')): self.request = self.response.request super(RequestException, self).__init__(*args, **kwargs)
'Build the path URL to use.'
@property def path_url(self):
url = [] p = urlsplit(self.url) path = p.path if (not path): path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) return ''.join(url)
'Encode parameters in a piece of data. Will successfully encode parameters when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.'
@staticmethod def _encode_params(data):
if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for (k, vs) in to_key_val_list(data): if (isinstance(vs, basestring) or (not hasattr(vs, '__iter__'))): vs = [vs] ...
'Build the body for a multipart/form-data request. Will successfully encode files when passed as a dict or a list of 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary if parameters are supplied as a dict.'
@staticmethod def _encode_files(files, data):
if (not files): raise ValueError('Files must be provided.') elif isinstance(data, basestring): raise ValueError('Data must not be a string.') new_fields = [] fields = to_key_val_list((data or {})) files = to_key_val_list((files or {})) for (field, val) in ...
'Properly register a hook.'
def register_hook(self, event, hook):
if (event not in self.hooks): raise ValueError(('Unsupported event specified, with event name "%s"' % event)) if isinstance(hook, collections.Callable): self.hooks[event].append(hook) elif hasattr(hook, '__iter__'): self.hooks[event].extend((h for h in hook if isins...
'Deregister a previously registered hook. Returns True if the hook existed, False if not.'
def deregister_hook(self, event, hook):
try: self.hooks[event].remove(hook) return True except ValueError: return False
'Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.'
def prepare(self):
p = PreparedRequest() p.prepare(method=self.method, url=self.url, headers=self.headers, files=self.files, data=self.data, params=self.params, auth=self.auth, cookies=self.cookies, hooks=self.hooks) return p
'Prepares the entire request with the given parameters.'
def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None):
self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files) self.prepare_auth(auth, url) self.prepare_hooks(hooks)
'Prepares the given HTTP method.'
def prepare_method(self, method):
self.method = method if (self.method is not None): self.method = self.method.upper()
'Prepares the given HTTP URL.'
def prepare_url(self, url, params):
try: url = unicode(url) except NameError: url = str(url) except UnicodeDecodeError: pass if ((':' in url) and (not url.lower().startswith('http'))): self.url = url return (scheme, auth, host, port, path, query, fragment) = parse_url(url) if (not scheme): ...
'Prepares the given HTTP headers.'
def prepare_headers(self, headers):
if headers: self.headers = CaseInsensitiveDict(((to_native_string(name), value) for (name, value) in headers.items())) else: self.headers = CaseInsensitiveDict()
'Prepares the given HTTP body data.'
def prepare_body(self, data, files):
body = None content_type = None length = None is_stream = all([hasattr(data, '__iter__'), (not isinstance(data, (basestring, list, tuple, dict)))]) try: length = super_len(data) except (TypeError, AttributeError, UnsupportedOperation): length = None if is_stream: body...
'Prepares the given HTTP auth data.'
def prepare_auth(self, auth, url=''):
if (auth is None): url_auth = get_auth_from_url(self.url) auth = (url_auth if any(url_auth) else None) if auth: if (isinstance(auth, tuple) and (len(auth) == 2)): auth = HTTPBasicAuth(*auth) r = auth(self) self.__dict__.update(r.__dict__) self.prepare_...
'Prepares the given HTTP cookie data.'
def prepare_cookies(self, cookies):
if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) if (cookie_header is not None): self.headers['Cookie'] = cookie_header
'Prepares the given hooks.'
def prepare_hooks(self, hooks):
for event in hooks: self.register_hook(event, hooks[event])
'Returns true if :attr:`status_code` is \'OK\'.'
def __bool__(self):
return self.ok
'Returns true if :attr:`status_code` is \'OK\'.'
def __nonzero__(self):
return self.ok
'Allows you to use a response as an iterator.'
def __iter__(self):
return self.iter_content(128)
'True if this Response is a well-formed HTTP redirect that could have been processed automatically (by :meth:`Session.resolve_redirects`).'
@property def is_redirect(self):
return (('location' in self.headers) and (self.status_code in REDIRECT_STATI))
'The apparent encoding, provided by the chardet library'
@property def apparent_encoding(self):
return chardet.detect(self.content)['encoding']
'Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. If decode_unicode i...
def iter_content(self, chunk_size=1, decode_unicode=False):
def generate(): try: try: for chunk in self.raw.stream(chunk_size, decode_content=True): (yield chunk) except IncompleteRead as e: raise ChunkedEncodingError(e) except DecodeError as e: raise ContentDecod...
'Iterates over the response data, one line at a time. When stream=True is set on the request, this avoids reading the content at once into memory for large responses.'
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None):
pending = None for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode): if (pending is not None): chunk = (pending + chunk) lines = chunk.splitlines() if (lines and lines[(-1)] and chunk and (lines[(-1)][(-1)] == chunk[(-1)])): pending...
'Content of the response, in bytes.'
@property def content(self):
if (self._content is False): try: if self._content_consumed: raise RuntimeError('The content for this response was already consumed') if (self.status_code == 0): self._content = None else: self._content ...
'Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using ``chardet``. The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you s...
@property def text(self):
content = None encoding = self.encoding if (not self.content): return str('') if (self.encoding is None): encoding = self.apparent_encoding try: content = str(self.content, encoding, errors='replace') except (LookupError, TypeError): content = str(self.content, er...
'Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.'
def json(self, **kwargs):
if ((not self.encoding) and (len(self.content) > 3)): encoding = guess_json_utf(self.content) if (encoding is not None): try: return json.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: pass return json.loads(self....
'Returns the parsed header links of the response, if any.'
@property def links(self):
header = self.headers.get('link') l = {} if header: links = parse_header_links(header) for link in links: key = (link.get('rel') or link.get('url')) l[key] = link return l
'Raises stored :class:`HTTPError`, if one occurred.'
def raise_for_status(self):
http_error_msg = '' if (400 <= self.status_code < 500): http_error_msg = ('%s Client Error: %s' % (self.status_code, self.reason)) elif (500 <= self.status_code < 600): http_error_msg = ('%s Server Error: %s' % (self.status_code, self.reason)) if http_error_msg: ...
'Releases the connection back to the pool. Once this method has been called the underlying ``raw`` object must not be accessed again. *Note: Should not normally need to be called explicitly.*'
def close(self):
return self.raw.release_conn()
'Takes the given response and tries digest-auth, if needed.'
def handle_401(self, r, **kwargs):
if (self.pos is not None): r.request.body.seek(self.pos) num_401_calls = getattr(self, 'num_401_calls', 1) s_auth = r.headers.get('www-authenticate', '') if (('digest' in s_auth.lower()) and (num_401_calls < 2)): setattr(self, 'num_401_calls', (num_401_calls + 1)) pat = re.compil...
'Receives a Response. Returns a generator of Responses.'
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None):
i = 0 while resp.is_redirect: prepared_request = req.copy() try: resp.content except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=False) if (i >= self.max_redirects): raise TooManyRedirects(('Exceeded...
'When being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss.'
def rebuild_auth(self, prepared_request, response):
headers = prepared_request.headers url = prepared_request.url if ('Authorization' in headers): original_parsed = urlparse(response.request.url) redirect_parsed = urlparse(url) if (original_parsed.hostname != redirect_parsed.hostname): del headers['Authorization'] new_...
'This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Auth...
def rebuild_proxies(self, prepared_request, proxies):
headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = (proxies.copy() if (proxies is not None) else {}) if (self.trust_env and (not should_bypass_proxies(url))): environ_proxies = get_environ_proxies(url) proxy = environ_proxies.get...
'Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request <Request>` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session\'s settings.'
def prepare_request(self, request):
cookies = (request.cookies or {}) if (not isinstance(cookies, cookielib.CookieJar)): cookies = cookiejar_from_dict(cookies) merged_cookies = merge_cookies(merge_cookies(RequestsCookieJar(), self.cookies), cookies) auth = request.auth if (self.trust_env and (not auth) and (not self.auth)): ...
'Constructs a :class:`Request <Request>`, prepares it and sends it. Returns :class:`Response <Response>` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Re...
def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None):
method = builtin_str(method) req = Request(method=method.upper(), url=url, headers=headers, files=files, data=(data or {}), params=(params or {}), auth=auth, cookies=cookies, hooks=hooks) prep = self.prepare_request(req) proxies = (proxies or {}) if self.trust_env: env_proxies = (get_environ...
'Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def get(self, url, **kwargs):
kwargs.setdefault('allow_redirects', True) return self.request('GET', url, **kwargs)
'Sends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def options(self, url, **kwargs):
kwargs.setdefault('allow_redirects', True) return self.request('OPTIONS', url, **kwargs)
'Sends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def head(self, url, **kwargs):
kwargs.setdefault('allow_redirects', False) return self.request('HEAD', url, **kwargs)
'Sends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def post(self, url, data=None, **kwargs):
return self.request('POST', url, data=data, **kwargs)
'Sends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def put(self, url, data=None, **kwargs):
return self.request('PUT', url, data=data, **kwargs)
'Sends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def patch(self, url, data=None, **kwargs):
return self.request('PATCH', url, data=data, **kwargs)
'Sends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes.'
def delete(self, url, **kwargs):
return self.request('DELETE', url, **kwargs)
'Send a given PreparedRequest.'
def send(self, request, **kwargs):
kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify) kwargs.setdefault('cert', self.cert) kwargs.setdefault('proxies', self.proxies) if (not isinstance(request, PreparedRequest)): raise ValueError('You can only send PreparedRequests.') allow_redir...
'Returns the appropriate connnection adapter for the given URL.'
def get_adapter(self, url):
for (prefix, adapter) in self.adapters.items(): if url.lower().startswith(prefix): return adapter raise InvalidSchema(("No connection adapters were found for '%s'" % url))
'Closes all adapters and as such the session'
def close(self):
for v in self.adapters.values(): v.close()
'Registers a connection adapter to a prefix. Adapters are sorted in descending order by key length.'
def mount(self, prefix, adapter):
self.adapters[prefix] = adapter keys_to_move = [k for k in self.adapters if (len(k) < len(prefix))] for key in keys_to_move: self.adapters[key] = self.adapters.pop(key)
'Like iteritems(), but with all lowercase keys.'
def lower_items(self):
return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
'Initializes a urllib3 PoolManager. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param connections: The number of urllib3 connection pools to cache. :param maxsize: The maximum number of connections to save in th...
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK):
self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block)
'Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :param verify: Whether we should actually...
def cert_verify(self, conn, url, verify, cert):
if (url.lower().startswith('https') and verify): cert_loc = None if (verify is not True): cert_loc = verify if (not cert_loc): cert_loc = DEFAULT_CA_BUNDLE_PATH if (not cert_loc): raise Exception('Could not find a suitable SSL CA ...
'Builds a :class:`Response <requests.Response>` object from a urllib3 response. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>` :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response. :param...
def build_response(self, req, resp):
response = Response() response.status_code = getattr(resp, 'status', None) response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {})) response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, byt...
'Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of proxies used on this request.'
def get_connection(self, url, proxies=None):
proxies = (proxies or {}) proxy = proxies.get(urlparse(url.lower()).scheme) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_headers = self.proxy_headers(proxy) if (not (proxy in self.proxy_manager)): self.proxy_manager[proxy] = proxy_from_url(proxy, proxy_...
'Disposes of any internal state. Currently, this just closes the PoolManager, which closes pooled connections.'
def close(self):
self.poolmanager.clear()
'Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapte...
def request_url(self, request, proxies):
proxies = (proxies or {}) scheme = urlparse(request.url).scheme proxy = proxies.get(scheme) if (proxy and (scheme != 'https')): (url, _) = urldefrag(request.url) else: url = request.path_url return url
'Add any headers needed by the connection. As of v2.0 this does nothing by default, but is left for overriding by users that subclass the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapter...
def add_headers(self, request, **kwargs):
pass
'Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed for use when subclassing the :cla...
def proxy_headers(self, proxy):
headers = {} (username, password) = get_auth_from_url(proxy) if (username and password): headers['Proxy-Authorization'] = _basic_auth_str(username, password) return headers
'Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request content. :param timeout: (optional) The timeout on the request. :param verify: (optional) Whether to verify SSL certificates. :param ...
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
conn = self.get_connection(request.url, proxies) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers(request) chunked = (not ((request.body is None) or ('Content-Length' in request.headers))) timeout = TimeoutSauce(connect=timeout, read=tim...
'Create working set from list of path entries (default=sys.path)'
def __init__(self, entries=None):
self.entries = [] self.entry_keys = {} self.by_key = {} self.callbacks = [] if (entries is None): entries = sys.path for entry in entries: self.add_entry(entry)
'Prepare the master working set.'
@classmethod def _build_master(cls):
ws = cls() try: from __main__ import __requires__ except ImportError: return ws try: ws.require(__requires__) except VersionConflict: return cls._build_from_requirements(__requires__) return ws
'Build a working set from a requirement spec. Rewrites sys.path.'
@classmethod def _build_from_requirements(cls, req_spec):
ws = cls([]) reqs = parse_requirements(req_spec) dists = ws.resolve(reqs, Environment()) for dist in dists: ws.add(dist) for entry in sys.path: if (entry not in ws.entries): ws.add_entry(entry) sys.path[:] = ws.entries return ws
'Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value mo...
def add_entry(self, entry):
self.entry_keys.setdefault(entry, []) self.entries.append(entry) for dist in find_distributions(entry, True): self.add(dist, entry, False)
'True if `dist` is the active distribution for its project'
def __contains__(self, dist):
return (self.by_key.get(dist.key) == dist)
'Find a distribution matching requirement `req` If there is an active distribution for the requested project, this returns it as long as it meets the version requirement specified by `req`. But, if there is an active distribution for the project and it does *not* meet the `req` requirement, ``VersionConflict`` is rais...
def find(self, req):
dist = self.by_key.get(req.key) if ((dist is not None) and (dist not in req)): raise VersionConflict(dist, req) else: return dist
'Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order).'
def iter_entry_points(self, group, name=None):
for dist in self: entries = dist.get_entry_map(group) if (name is None): for ep in entries.values(): (yield ep) elif (name in entries): (yield entries[name])
'Locate distribution for `requires` and run `script_name` script'
def run_script(self, requires, script_name):
ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name self.require(requires)[0].run_script(script_name, ns)
'Yield distributions for non-duplicate projects in the working set The yield order is the order in which the items\' path entries were added to the working set.'
def __iter__(self):
seen = {} for item in self.entries: if (item not in self.entry_keys): continue for key in self.entry_keys[item]: if (key not in seen): seen[key] = 1 (yield self.by_key[key])
'Add `dist` to working set, associated with `entry` If `entry` is unspecified, it defaults to the ``.location`` of `dist`. On exit from this routine, `entry` is added to the end of the working set\'s ``.entries`` (if it wasn\'t already present). `dist` is only added to the working set if it\'s for a project that doesn\...
def add(self, dist, entry=None, insert=True, replace=False):
if insert: dist.insert_on(self.entries, entry) if (entry is None): entry = dist.location keys = self.entry_keys.setdefault(entry, []) keys2 = self.entry_keys.setdefault(dist.location, []) if ((not replace) and (dist.key in self.by_key)): return self.by_key[dist.key] = dis...
'List all distributions needed to (recursively) meet `requirements` `requirements` must be a sequence of ``Requirement`` objects. `env`, if supplied, should be an ``Environment`` instance. If not supplied, it defaults to all distributions available within any entry or distribution in the working set. `installer`, if...
def resolve(self, requirements, env=None, installer=None, replace_conflicting=False):
requirements = list(requirements)[::(-1)] processed = {} best = {} to_activate = [] while requirements: req = requirements.pop(0) if (req in processed): continue dist = best.get(req.key) if (dist is None): dist = self.by_key.get(req.key) ...
'Find all activatable distributions in `plugin_env` Example usage:: distributions, errors = working_set.find_plugins( Environment(plugin_dirlist) map(working_set.add, distributions) # add plugins+libs to sys.path print \'Could not load\', errors # display errors The `plugin_env` should be an ``Environment`` ins...
def find_plugins(self, plugin_env, full_env=None, installer=None, fallback=True):
plugin_projects = list(plugin_env) plugin_projects.sort() error_info = {} distributions = {} if (full_env is None): env = Environment(self.entries) env += plugin_env else: env = (full_env + plugin_env) shadow_set = self.__class__([]) list(map(shadow_set.add, self)...