desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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 queue.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) host = _ipv6_host(host).lower() 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, po...
'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=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw):
if (headers is None): headers = self.headers if (not isinstance(retries, Retry)): retries = Retry.from_int(retries, redirect=redirect, default=self.retries) if (release_conn is None): release_conn = response_kw.get('preload_content', True) if (assert_same_host and (not self.is_sa...
'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, ca_cert_dir=self.ca_cert_dir, assert_hostname=self.assert_hostname, assert_fingerprint=self.assert_fingerprint) conn.ssl_version = self.ssl_...
'Establish tunnel connection early, because otherwise httplib would improperly set Host: header to proxy\'s IP:port.'
def _prepare_proxy(self, conn):
try: set_tunnel = conn.set_tunnel except AttributeError: set_tunnel = conn._set_tunnel if ((sys.version_info <= (2, 6, 4)) and (not self.proxy_headers)): set_tunnel(self.host, self.port) else: set_tunnel(self.host, self.port, self.proxy_headers) conn.connect()
'Return a fresh :class:`httplib.HTTPSConnection`.'
def _new_conn(self):
self.num_connections += 1 log.debug('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 n...
'Called right before a request is made, after the socket is created.'
def _validate_conn(self, conn):
super(HTTPSConnectionPool, self)._validate_conn(conn) if (not getattr(conn, 'sock', None)): conn.connect() if (not conn.is_verified): warnings.warn('Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https:...
'Establish a new connection via the SOCKS proxy.'
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 = socks.create_connection((self.host, self.port), proxy_type=self._socks_options['socks_version'], proxy_addr=...
'A context manager that can be used to wrap calls that do I/O from SecureTransport. If any of the I/O callbacks hit an exception, this context manager will correctly propagate the exception after the fact. This avoids silently swallowing those exceptions. It also correctly forces the socket closed.'
@contextlib.contextmanager def _raise_on_error(self):
self._exception = None (yield) if (self._exception is not None): (exception, self._exception) = (self._exception, None) self.close() raise exception
'Sets up the allowed ciphers. By default this matches the set in util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done custom and doesn\'t allow changing at this time, mostly because parsing OpenSSL cipher strings is going to be a freaking nightmare.'
def _set_ciphers(self):
ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES) result = Security.SSLSetEnabledCiphers(self.context, ciphers, len(CIPHER_SUITES)) _assert_no_error(result)
'Called when we have set custom validation. We do this in two cases: first, when cert validation is entirely disabled; and second, when using a custom trust DB.'
def _custom_validate(self, verify, trust_bundle):
if (not verify): return if os.path.isfile(trust_bundle): with open(trust_bundle, 'rb') as f: trust_bundle = f.read() cert_array = None trust = Security.SecTrustRef() try: cert_array = _cert_array_from_pem(trust_bundle) result = Security.SSLCopyPeerTrust(se...
'Actually performs the TLS handshake. This is run automatically by wrapped socket, and shouldn\'t be needed in user code.'
def handshake(self, server_hostname, verify, trust_bundle, min_version, max_version, client_cert, client_key, client_key_passphrase):
self.context = Security.SSLCreateContext(None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType) result = Security.SSLSetIOFuncs(self.context, _read_callback_pointer, _write_callback_pointer) _assert_no_error(result) with _connection_ref_lock: handle = (id(self) % 2147483647) w...
'SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file.'
@property def check_hostname(self):
return True
'SecureTransport cannot have its hostname checking disabled. For more, see the comment on getpeercert() in this file.'
@check_hostname.setter def check_hostname(self, value):
pass
'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, headers=None, **urlopen_kw):
if (headers is None): headers = self.headers extra_kw = {'headers': headers} extra_kw.update(urlopen_kw) if fields: url += ('?' + urlencode(fields)) return self.urlopen(method, url, **extra_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 (headers is None): headers = self.headers extra_kw = {'headers': {}} if fields: if ('body' in urlopen_kw): raise TypeError("request got values for both 'fields' and 'body', can only specify one.") if encode_multipart: (body,...
'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 tuples. Order is retained if data is a list of tuples but arbitrary if parameters are supplied as a dict. The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype) or 4-tup...
@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, json=self.json, 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, json=None):
self.prepare_method(method) self.prepare_url(url, params) self.prepare_headers(headers) self.prepare_cookies(cookies) self.prepare_body(data, files, json) 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 = to_native_string(self.method.upper())
'Prepares the given HTTP URL.'
def prepare_url(self, url, params):
if isinstance(url, bytes): url = url.decode('utf8') else: url = (unicode(url) if is_py2 else str(url)) url = url.lstrip() if ((':' in url) and (not url.lower().startswith('http'))): self.url = url return try: (scheme, auth, host, port, path, query, fragment) =...
'Prepares the given HTTP headers.'
def prepare_headers(self, headers):
self.headers = CaseInsensitiveDict() if headers: for header in headers.items(): check_header_validity(header) (name, value) = header self.headers[to_native_string(name)] = value
'Prepares the given HTTP body data.'
def prepare_body(self, data, files, json=None):
body = None content_type = None if ((not data) and (json is not None)): content_type = 'application/json' body = complexjson.dumps(json) if (not isinstance(body, bytes)): body = body.encode('utf-8') is_stream = all([hasattr(data, '__iter__'), (not isinstance(data, (ba...
'Prepare Content-Length header based on request method and body'
def prepare_content_length(self, body):
if (body is not None): length = super_len(body) if length: self.headers['Content-Length'] = builtin_str(length) elif ((self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None)): self.headers['Content-Length'] = '0'
'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. This function eventually generates a ``Cookie`` header from the given cookies using cookielib. Due to cookielib\'s design, the header will not be regenerated if it already exists, meaning this function can only be called once for the life of the :class:`PreparedRequest <PreparedReq...
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):
hooks = (hooks or []) for event in hooks: self.register_hook(event, hooks[event])
'Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK`...
def __bool__(self):
return self.ok
'Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK`...
def __nonzero__(self):
return self.ok
'Allows you to use a response as an iterator.'
def __iter__(self):
return self.iter_content(128)
'Returns True if :attr:`status_code` is less than 400. This attribute checks if the status code of the response is between 400 and 600 to see if there was a client error or a server error. If the status code, is between 200 and 400, this will return True. This is **not** a check to see if the response code is ``200 OK`...
@property def ok(self):
try: self.raise_for_status() except HTTPError: return False return True
'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))
'True if this Response one of the permanent versions of redirect'
@property def is_permanent_redirect(self):
return (('location' in self.headers) and (self.status_code in (codes.moved_permanently, codes.permanent_redirect)))
'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. chunk_size must be ...
def iter_content(self, chunk_size=1, decode_unicode=False):
def generate(): if hasattr(self.raw, 'stream'): try: for chunk in self.raw.stream(chunk_size, decode_content=True): (yield chunk) except ProtocolError as e: raise ChunkedEncodingError(e) except DecodeError as e: ...
'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. .. note:: This method is not reentrant safe.'
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=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) if delimiter: lines = chunk.split(delimiter) else: lines = chunk.splitlines() if (lines and...
'Content of the response, in bytes.'
@property def content(self):
if (self._content is False): if self._content_consumed: raise RuntimeError('The content for this response was already consumed') if ((self.status_code == 0) or (self.raw is None)): self._content = None else: self._content = (bytes().jo...
'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. :raises ValueError: If the response body does not contain valid json.'
def json(self, **kwargs):
if ((not self.encoding) and self.content and (len(self.content) > 3)): encoding = guess_json_utf(self.content) if (encoding is not None): try: return complexjson.loads(self.content.decode(encoding), **kwargs) except UnicodeDecodeError: pass ...
'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 isinstance(self.reason, bytes): try: reason = self.reason.decode('utf-8') except UnicodeDecodeError: reason = self.reason.decode('iso-8859-1') else: reason = self.reason if (400 <= self.status_code < 500): http_error_msg = (u...
'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):
if (not self._content_consumed): self.raw.close() release_conn = getattr(self.raw, 'release_conn', None) if (release_conn is not None): release_conn()
':rtype: str'
def build_digest_header(self, method, url):
realm = self._thread_local.chal['realm'] nonce = self._thread_local.chal['nonce'] qop = self._thread_local.chal.get('qop') algorithm = self._thread_local.chal.get('algorithm') opaque = self._thread_local.chal.get('opaque') hash_utf8 = None if (algorithm is None): _algorithm = 'MD5' ...
'Reset num_401_calls counter on redirects.'
def handle_redirect(self, r, **kwargs):
if r.is_redirect: self._thread_local.num_401_calls = 1
'Takes the given response and tries digest-auth, if needed. :rtype: requests.Response'
def handle_401(self, r, **kwargs):
if (not (400 <= r.status_code < 500)): self._thread_local.num_401_calls = 1 return r if (self._thread_local.pos is not None): r.request.body.seek(self._thread_local.pos) s_auth = r.headers.get('www-authenticate', '') if (('digest' in s_auth.lower()) and (self._thread_local.num_40...
'Receives a Response. Returns a redirect URI or ``None``'
def get_redirect_target(self, resp):
if resp.is_redirect: location = resp.headers['location'] if is_py3: location = location.encode('latin1') return to_native_string(location, 'utf8') return None
'Receives a Response. Returns a generator of Responses.'
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None, **adapter_kwargs):
hist = [] url = self.get_redirect_target(resp) while url: prepared_request = req.copy() hist.append(resp) resp.history = hist[1:] try: resp.content except (ChunkedEncodingError, ContentDecodingError, RuntimeError): resp.raw.read(decode_content=...
'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):
proxies = (proxies if (proxies is not None) else {}) headers = prepared_request.headers url = prepared_request.url scheme = urlparse(url).scheme new_proxies = proxies.copy() no_proxy = proxies.get('no_proxy') bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy) if (self.trust_env...
'When being redirected we may want to change the method of the request based on certain specs or browser behavior.'
def rebuild_method(self, prepared_request, response):
method = prepared_request.method if ((response.status_code == codes.see_other) and (method != 'HEAD')): method = 'GET' if ((response.status_code == codes.found) and (method != 'HEAD')): method = 'GET' if ((response.status_code == codes.moved) and (method == 'POST')): method = 'GE...
'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. :rtype: requests....
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, json=None):
req = Request(method=method.upper(), url=url, headers=headers, files=files, data=(data or {}), json=json, params=(params or {}), auth=auth, cookies=cookies, hooks=hooks) prep = self.prepare_request(req) proxies = (proxies or {}) settings = self.merge_environment_settings(prep.url, proxies, stream, verif...
'Sends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response'
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. :rtype: requests.Response'
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. :rtype: requests.Response'
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 json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional ...
def post(self, url, data=None, json=None, **kwargs):
return self.request('POST', url, data=data, json=json, **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. :rtype: requests.Response'
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. :rtype: requests.Response'
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. :rtype: requests.Response'
def delete(self, url, **kwargs):
return self.request('DELETE', url, **kwargs)
'Send a given PreparedRequest. :rtype: requests.Response'
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 isinstance(request, Request): raise ValueError('You can only send PreparedRequests.') allow_redirects = kwargs....
'Check the environment and merge it with some settings. :rtype: dict'
def merge_environment_settings(self, url, proxies, stream, verify, cert):
if self.trust_env: no_proxy = (proxies.get('no_proxy') if (proxies is not None) else None) env_proxies = get_environ_proxies(url, no_proxy=no_proxy) for (k, v) in env_proxies.items(): proxies.setdefault(k, v) if ((verify is True) or (verify is None)): verify =...
'Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter'
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())
'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) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect ti...
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
raise NotImplementedError
'Cleans up adapter specific items.'
def close(self):
raise NotImplementedError
'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, **pool_kwargs):
self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, strict=True, **pool_kwargs)
'Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kwargs: Extra keyword arguments used to con...
def proxy_manager_for(self, proxy, **proxy_kwargs):
if (proxy in self.proxy_manager): manager = self.proxy_manager[proxy] elif proxy.lower().startswith('socks'): (username, password) = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager(proxy, username=username, password=password, num_pools=self._pool_connecti...
'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: Either a boolean, in which...
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) or (not os.path.exists(cert_loc))): raise IOError('Could not f...
'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. :rt...
def get_connection(self, url, proxies=None):
proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, 'http') proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager....
'Disposes of any internal state. Currently, this closes the PoolManager and any active ProxyManager, which closes any pooled connections.'
def close(self):
self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.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):
proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = (proxy and (scheme != 'https')) using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith('socks') 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: 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) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect ti...
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))) if isinstance(timeout, tuple): try: ...
'Recursively check an element'
def check_element(self, element_id, element_type, element_name, element_level, element_position, element_size, element_data, element, ignore_element_types=None, ignore_element_names=None, max_level=None):
self.assertTrue((element.id == element_id)) self.assertTrue((element.type == element_type)) self.assertTrue((element.name == element_name)) self.assertTrue((element.level == element_level)) self.assertTrue((element.position == element_position)) self.assertTrue((element.size == element_size)) ...
'Load the :class:`Info` from an :class:`~enzyme.parsers.ebml.Element` :param element: the Info element :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
title = element.get('Title') duration = element.get('Duration') date_utc = element.get('DateUTC') timecode_scale = element.get('TimecodeScale') muxing_app = element.get('MuxingApp') writing_app = element.get('WritingApp') return cls(title, duration, date_utc, timecode_scale, muxing_app, writ...
'Load the :class:`Track` from an :class:`~enzyme.parsers.ebml.Element` :param element: the Track element :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
type = element.get('TrackType') number = element.get('TrackNumber', 0) name = element.get('Name') language = element.get('Language') enabled = bool(element.get('FlagEnabled', 1)) default = bool(element.get('FlagDefault', 1)) forced = bool(element.get('FlagForced', 0)) lacing = bool(eleme...
'Load the :class:`VideoTrack` from an :class:`~enzyme.parsers.ebml.Element` :param element: the Track element with :data:`VIDEO_TRACK` TrackType :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
videotrack = super(VideoTrack, cls).fromelement(element) videotrack.width = element['Video'].get('PixelWidth', 0) videotrack.height = element['Video'].get('PixelHeight', 0) videotrack.interlaced = bool(element['Video'].get('FlagInterlaced', False)) videotrack.stereo_mode = element['Video'].get('Ster...
'Load the :class:`AudioTrack` from an :class:`~enzyme.parsers.ebml.Element` :param element: the Track element with :data:`AUDIO_TRACK` TrackType :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
audiotrack = super(AudioTrack, cls).fromelement(element) audiotrack.sampling_frequency = element['Audio'].get('SamplingFrequency', 8000.0) audiotrack.channels = element['Audio'].get('Channels', 1) audiotrack.output_sampling_frequency = element['Audio'].get('OutputSamplingFrequency') audiotrack.bit_d...
'Load the :class:`Tag` from an :class:`~enzyme.parsers.ebml.Element` :param element: the Tag element :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
targets = (element['Targets'] if ('Targets' in element) else []) simpletags = [SimpleTag.fromelement(s) for s in element if (s.name == 'SimpleTag')] return cls(targets, simpletags)
'Load the :class:`SimpleTag` from an :class:`~enzyme.parsers.ebml.Element` :param element: the SimpleTag element :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
name = element.get('TagName') language = element.get('TagLanguage', 'und') default = element.get('TagDefault', True) string = element.get('TagString') binary = element.get('TagBinary') return cls(name, language, default, string, binary)
'Load the :class:`Chapter` from an :class:`~enzyme.parsers.ebml.Element` :param element: the ChapterAtom element :type element: :class:`~enzyme.parsers.ebml.Element`'
@classmethod def fromelement(cls, element):
start = timedelta(microseconds=(element.get('ChapterTimeStart') // 1000)) hidden = element.get('ChapterFlagHidden', False) enabled = element.get('ChapterFlagEnabled', True) end = element.get('ChapterTimeEnd') chapterdisplays = [c for c in element if (c.name == 'ChapterDisplay')] if (len(chapterd...
'Load children :class:`Elements <Element>` with level lower or equal to the `max_level` from the `stream` according to the `specs` :param stream: file-like object from which to read :param dict specs: see :ref:`specs` :param int max_level: maximum level for children elements :param list ignore_element_types: list of el...
def load(self, stream, specs, ignore_element_types=None, ignore_element_names=None, max_level=None):
self.data = parse(stream, specs, self.size, ignore_element_types, ignore_element_names, max_level)
'Convenience method for ``master_element[name].data if name in master_element else default`` :param string name: the name of the child to get :param default: default value if `name` is not in the :class:`MasterElement` :return: the data of the child :class:`Element` or `default`'
def get(self, name, default=None):
if (name not in self): return default element = self[name] if (element.type == MASTER): raise ValueError(('%s is a MasterElement' % name)) return element.data
'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
'Get the subtype class for a pointer'
@classmethod def _get_type(cls, ptr):
return cls.__types.get(lib.g_base_info_get_type(ptr), cls)
'Might return a struct'
def lookup_name_fast(self, name):
if (name in self.__names): return self.__names[name] count = self.__get_count_cached() lo = 0 hi = count while (lo < hi): mid = ((lo + hi) // 2) if (self.__get_name_cached(mid) < name): lo = (mid + 1) else: hi = mid if ((lo != count) and (s...
'Returns a struct if one exists'
def lookup_name_slow(self, name):
for index in xrange(self.__get_count_cached()): if (self.__get_name_cached(index) == name): return self.__get_info_cached(index)
'Returns a struct if one exists'
def lookup_name(self, name):
try: info = self._get_by_name(self._source, name) except NotImplementedError: pass else: if info: return info return info = self.lookup_name_fast(name) if info: return info return self.lookup_name_slow(name)