text
stringlengths
81
112k
Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` def fetch_errors_from(self, path): """ Returns all errors for a particular path. :param path: :class:`tuple` of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorList` """ node = self.fetch_node_from(path) if node is not None: return node.errors else: return ErrorList()
Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` def fetch_node_from(self, path): """ Returns a node for a path. :param path: Tuple of :term:`hashable` s. :rtype: :class:`~cerberus.errors.ErrorTreeNode` or :obj:`None` """ context = self for key in path: context = context[key] if context is None: break return context
Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. def _insert_error(self, path, node): """ Adds an error or sub-tree to :attr:tree. :param path: Path to the error. :type path: Tuple of strings and integers. :param node: An error message or a sub-tree. :type node: String or dictionary. """ field = path[0] if len(path) == 1: if field in self.tree: subtree = self.tree[field].pop() self.tree[field] += [node, subtree] else: self.tree[field] = [node, {}] elif len(path) >= 1: if field not in self.tree: self.tree[field] = [{}] subtree = self.tree[field][-1] if subtree: new = self.__class__(tree=copy(subtree)) else: new = self.__class__() new._insert_error(path[1:], node) subtree.update(new.tree)
Recursively rewrites the error path to correctly represent logic errors def _rewrite_error_path(self, error, offset=0): """ Recursively rewrites the error path to correctly represent logic errors """ if error.is_logic_error: self._rewrite_logic_error_path(error, offset) elif error.is_group_error: self._rewrite_group_error_path(error, offset)
Dispatches a hook dictionary on a given piece of data. def dispatch_hook(key, hooks, hook_data, **kwargs): """Dispatches a hook dictionary on a given piece of data.""" hooks = hooks or {} hooks = hooks.get(key) if hooks: if hasattr(hooks, '__call__'): hooks = [hooks] for hook in hooks: _hook_data = hook(hook_data, **kwargs) if _hook_data is not None: hook_data = _hook_data return hook_data
This script is used to set, get or unset values from a .env file. def cli(ctx, file, quote): '''This script is used to set, get or unset values from a .env file.''' ctx.obj = {} ctx.obj['FILE'] = file ctx.obj['QUOTE'] = quote
Display all the stored key/value. def list(ctx): '''Display all the stored key/value.''' file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) for k, v in dotenv_as_dict.items(): click.echo('%s=%s' % (k, v))
Store the given key/value. def set(ctx, key, value): '''Store the given key/value.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key, value = set_key(file, key, value, quote) if success: click.echo('%s=%s' % (key, value)) else: exit(1)
Retrieve the value for the given key. def get(ctx, key): '''Retrieve the value for the given key.''' file = ctx.obj['FILE'] stored_value = get_key(file, key) if stored_value: click.echo('%s=%s' % (key, stored_value)) else: exit(1)
Removes the given key. def unset(ctx, key): '''Removes the given key.''' file = ctx.obj['FILE'] quote = ctx.obj['QUOTE'] success, key = unset_key(file, key, quote) if success: click.echo("Successfully removed %s" % key) else: exit(1)
Run command with environment variables present. def run(ctx, commandline): """Run command with environment variables present.""" file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dotenv_as_dict) exit(ret)
Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. def _is_installation_local(name): """Check whether the distribution is in the current Python installation. This is used to distinguish packages seen by a virtual environment. A venv may be able to see global packages, but we don't want to mess with them. """ loc = os.path.normcase(pkg_resources.working_set.by_key[name].location) pre = os.path.normcase(sys.prefix) return os.path.commonprefix([loc, pre]) == pre
Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed packages: * `uptodate`: These match the specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`. def _group_installed_names(packages): """Group locally installed packages based on given specifications. `packages` is a name-package mapping that are used as baseline to determine how the installed package should be grouped. Returns a 3-tuple of disjoint sets, all containing names of installed packages: * `uptodate`: These match the specifications. * `outdated`: These installations are specified, but don't match the specifications in `packages`. * `unneeded`: These are installed, but not specified in `packages`. """ groupcoll = GroupCollection(set(), set(), set(), set()) for distro in pkg_resources.working_set: name = distro.key try: package = packages[name] except KeyError: groupcoll.unneeded.add(name) continue r = requirementslib.Requirement.from_pipfile(name, package) if not r.is_named: # Always mark non-named. I think pip does something similar? groupcoll.outdated.add(name) elif not _is_up_to_date(distro, r.get_version()): groupcoll.outdated.add(name) else: groupcoll.uptodate.add(name) return groupcoll
Prepare paths for distlib.wheel.Wheel to install into. def _build_paths(): """Prepare paths for distlib.wheel.Wheel to install into. """ paths = sysconfig.get_paths() return { "prefix": sys.prefix, "data": paths["data"], "scripts": paths["scripts"], "headers": paths["include"], "purelib": paths["purelib"], "platlib": paths["platlib"], }
Dumps a TOMLDocument into a string. def dumps(data): # type: (_TOMLDocument) -> str """ Dumps a TOMLDocument into a string. """ if not isinstance(data, _TOMLDocument) and isinstance(data, dict): data = item(data) return data.as_string()
Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. def findall(self): """Find all files under the base and set ``allfiles`` to the absolute pathnames of files found. """ from stat import S_ISREG, S_ISDIR, S_ISLNK self.allfiles = allfiles = [] root = self.base stack = [root] pop = stack.pop push = stack.append while stack: root = pop() names = os.listdir(root) for name in names: fullname = os.path.join(root, name) # Avoid excess stat calls -- just one will do, thank you! stat = os.stat(fullname) mode = stat.st_mode if S_ISREG(mode): allfiles.append(fsdecode(fullname)) elif S_ISDIR(mode) and not S_ISLNK(mode): push(fullname)
Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. def add(self, item): """ Add a file to the manifest. :param item: The pathname to add. This can be relative to the base. """ if not item.startswith(self.prefix): item = os.path.join(self.base, item) self.files.add(os.path.normpath(item))
Return sorted files in directory order def sorted(self, wantdirs=False): """ Return sorted files in directory order """ def add_dir(dirs, d): dirs.add(d) logger.debug('add_dir added %s', d) if d != self.base: parent, _ = os.path.split(d) assert parent not in ('', '/') add_dir(dirs, parent) result = set(self.files) # make a copy! if wantdirs: dirs = set() for f in result: add_dir(dirs, os.path.dirname(f)) result |= dirs return [os.path.join(*path_tuple) for path_tuple in sorted(os.path.split(path) for path in result)]
Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs.python.org/distutils/sourcedist.html#commands def process_directive(self, directive): """ Process a directive which either adds some files from ``allfiles`` to ``files``, or removes some files from ``files``. :param directive: The directive to process. This should be in a format compatible with distutils ``MANIFEST.in`` files: http://docs.python.org/distutils/sourcedist.html#commands """ # Parse the line: split it up, make sure the right number of words # is there, and return the relevant words. 'action' is always # defined: it's the first word of the line. Which of the other # three are defined depends on the action; it'll be either # patterns, (dir and patterns), or (dirpattern). action, patterns, thedir, dirpattern = self._parse_directive(directive) # OK, now we know that the action is valid and we have the # right number of words on the line for that action -- so we # can proceed with minimal error-checking. if action == 'include': for pattern in patterns: if not self._include_pattern(pattern, anchor=True): logger.warning('no files found matching %r', pattern) elif action == 'exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=True) #if not found: # logger.warning('no previously-included files ' # 'found matching %r', pattern) elif action == 'global-include': for pattern in patterns: if not self._include_pattern(pattern, anchor=False): logger.warning('no files found matching %r ' 'anywhere in distribution', pattern) elif action == 'global-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, anchor=False) #if not found: # logger.warning('no previously-included files ' # 'matching %r found anywhere in ' # 'distribution', pattern) elif action == 'recursive-include': for pattern in patterns: if not self._include_pattern(pattern, prefix=thedir): logger.warning('no files found matching %r ' 'under directory %r', pattern, thedir) elif action == 'recursive-exclude': for pattern in patterns: found = self._exclude_pattern(pattern, prefix=thedir) #if not found: # logger.warning('no previously-included files ' # 'matching %r found under directory %r', # pattern, thedir) elif action == 'graft': if not self._include_pattern(None, prefix=dirpattern): logger.warning('no directories found matching %r', dirpattern) elif action == 'prune': if not self._exclude_pattern(None, prefix=dirpattern): logger.warning('no previously-included directories found ' 'matching %r', dirpattern) else: # pragma: no cover # This should never happen, as it should be caught in # _parse_template_line raise DistlibException( 'invalid action %r' % action)
Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns def _parse_directive(self, directive): """ Validate a directive. :param directive: The directive to validate. :return: A tuple of action, patterns, thedir, dir_patterns """ words = directive.split() if len(words) == 1 and words[0] not in ('include', 'exclude', 'global-include', 'global-exclude', 'recursive-include', 'recursive-exclude', 'graft', 'prune'): # no action given, let's use the default 'include' words.insert(0, 'include') action = words[0] patterns = thedir = dir_pattern = None if action in ('include', 'exclude', 'global-include', 'global-exclude'): if len(words) < 2: raise DistlibException( '%r expects <pattern1> <pattern2> ...' % action) patterns = [convert_path(word) for word in words[1:]] elif action in ('recursive-include', 'recursive-exclude'): if len(words) < 3: raise DistlibException( '%r expects <dir> <pattern1> <pattern2> ...' % action) thedir = convert_path(words[1]) patterns = [convert_path(word) for word in words[2:]] elif action in ('graft', 'prune'): if len(words) != 2: raise DistlibException( '%r expects a single <dir_pattern>' % action) dir_pattern = convert_path(words[1]) else: raise DistlibException('unknown action %r' % action) return action, patterns, thedir, dir_pattern
Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return True if files are found. def _include_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Select strings (presumably filenames) from 'self.files' that match 'pattern', a Unix-style wildcard (glob) pattern. Patterns are not quite the same as implemented by the 'fnmatch' module: '*' and '?' match non-special characters, where "special" is platform-dependent: slash on Unix; colon, slash, and backslash on DOS/Windows; and colon on Mac OS. If 'anchor' is true (the default), then the pattern match is more stringent: "*.py" will match "foo.py" but not "foo/bar.py". If 'anchor' is false, both of these will match. If 'prefix' is supplied, then only filenames starting with 'prefix' (itself a pattern) and ending with 'pattern', with anything in between them, will match. 'anchor' is ignored in this case. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and 'pattern' is assumed to be either a string containing a regex or a regex object -- no translation is done, the regex is just compiled and used as-is. Selected strings will be added to self.files. Return True if files are found. """ # XXX docstring lying about what the special chars are? found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) # delayed loading of allfiles list if self.allfiles is None: self.findall() for name in self.allfiles: if pattern_re.search(name): self.files.add(name) found = True return found
Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions def _exclude_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Remove strings (presumably filenames) from 'files' that match 'pattern'. Other parameters are the same as for 'include_pattern()', above. The list 'self.files' is modified in place. Return True if files are found. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when packaging source distributions """ found = False pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex) for f in list(self.files): if pattern_re.search(f): self.files.remove(f) found = True return found
Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). def _translate_pattern(self, pattern, anchor=True, prefix=None, is_regex=False): """Translate a shell-like wildcard pattern to a compiled regular expression. Return the compiled regex. If 'is_regex' true, then 'pattern' is directly compiled to a regex (if it's a string) or just returned as-is (assumes it's a regex object). """ if is_regex: if isinstance(pattern, str): return re.compile(pattern) else: return pattern if _PYTHON_VERSION > (3, 2): # ditch start and end characters start, _, end = self._glob_to_re('_').partition('_') if pattern: pattern_re = self._glob_to_re(pattern) if _PYTHON_VERSION > (3, 2): assert pattern_re.startswith(start) and pattern_re.endswith(end) else: pattern_re = '' base = re.escape(os.path.join(self.base, '')) if prefix is not None: # ditch end of pattern character if _PYTHON_VERSION <= (3, 2): empty_pattern = self._glob_to_re('') prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)] else: prefix_re = self._glob_to_re(prefix) assert prefix_re.startswith(start) and prefix_re.endswith(end) prefix_re = prefix_re[len(start): len(prefix_re) - len(end)] sep = os.sep if os.sep == '\\': sep = r'\\' if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + sep.join((prefix_re, '.*' + pattern_re)) else: pattern_re = pattern_re[len(start): len(pattern_re) - len(end)] pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep, pattern_re, end) else: # no prefix -- respect anchor flag if anchor: if _PYTHON_VERSION <= (3, 2): pattern_re = '^' + base + pattern_re else: pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):]) return re.compile(pattern_re)
Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). def _glob_to_re(self, pattern): """Translate a shell-like glob pattern to a regular expression. Return a string containing the regex. Differs from 'fnmatch.translate()' in that '*' does not match "special characters" (which are platform-specific). """ pattern_re = fnmatch.translate(pattern) # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix, # and by extension they shouldn't match such "special characters" under # any OS. So change all non-escaped dots in the RE to match any # character except the special characters (currently: just os.sep). sep = os.sep if os.sep == '\\': # we're using a regex to manipulate a regex, so we need # to escape the backslash twice sep = r'\\\\' escaped = r'\1[^%s]' % sep pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re) return pattern_re
Blocking expect def expect_loop(self, timeout=-1): """Blocking expect""" spawn = self.spawn if timeout is not None: end_time = time.time() + timeout try: incoming = spawn.buffer spawn._buffer = spawn.buffer_type() spawn._before = spawn.buffer_type() while True: idx = self.new_data(incoming) # Keep reading until exception or return. if idx is not None: return idx # No match at this point if (timeout is not None) and (timeout < 0): return self.timeout() # Still have time left, so read more data incoming = spawn.read_nonblocking(spawn.maxread, timeout) if self.spawn.delayafterread is not None: time.sleep(self.spawn.delayafterread) if timeout is not None: timeout = end_time - time.time() except EOF as e: return self.eof(e) except TIMEOUT as e: return self.timeout(e) except: self.errored() raise
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): """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' """ key_lower = key.lower() new_vals = [key, val] # Keep the common case aka no item present as fast as possible vals = self._container.setdefault(key_lower, new_vals) if new_vals is not vals: vals.append(val)
Generic import function for any type of header-like object. Adapted version of MutableMapping.update in order to insert items with self.add instead of self.__setitem__ def extend(self, *args, **kwargs): """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__ """ if len(args) > 1: raise TypeError("extend() takes at most 1 positional " "arguments ({0} given)".format(len(args))) other = args[0] if len(args) >= 1 else () if isinstance(other, HTTPHeaderDict): for key, val in other.iteritems(): self.add(key, val) elif isinstance(other, Mapping): for key in other: self.add(key, other[key]) elif hasattr(other, "keys"): for key in other.keys(): self.add(key, other[key]) else: for key, value in other: self.add(key, value) for key, value in kwargs.items(): self.add(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, default=__marker): """Returns a list of all the values for the named field. Returns an empty list if the key doesn't exist.""" try: vals = self._container[key.lower()] except KeyError: if default is self.__marker: return [] return default else: return vals[1:]
Iterate over all header lines, including duplicate ones. def iteritems(self): """Iterate over all header lines, including duplicate ones.""" for key in self: vals = self._container[key.lower()] for val in vals[1:]: yield vals[0], val
Iterate over all headers, merging duplicate ones together. def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = self._container[key.lower()] yield val[0], ', '.join(val[1:])
Read headers from a Python 2 httplib message object. def from_httplib(cls, message): # Python 2 """Read headers from a Python 2 httplib message object.""" # python2.7 does not expose a proper API for exporting multiheaders # efficiently. This function re-reads raw lines from the message # object and extracts the multiheaders properly. obs_fold_continued_leaders = (' ', '\t') headers = [] for line in message.headers: if line.startswith(obs_fold_continued_leaders): if not headers: # We received a header line that starts with OWS as described # in RFC-7230 S3.2.4. This indicates a multiline header, but # there exists no previous header to which we can attach it. raise InvalidHeader( 'Header continuation with no previous header: %s' % line ) else: key, value = headers[-1] headers[-1] = (key, value + ' ' + line.strip()) continue key, value = line.split(':', 1) headers.append((key, value.strip())) return cls(headers)
Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object def extract_cookies_to_jar(jar, request, response): """Extract the cookies from the response into a CookieJar. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar) :param request: our own requests.Request object :param response: urllib3.HTTPResponse object """ if not (hasattr(response, '_original_response') and response._original_response): return # the _original_response field is the wrapped httplib.HTTPResponse object, req = MockRequest(request) # pull out the HTTPMessage with the headers and put it in the mock: res = MockResponse(response._original_response.msg) jar.extract_cookies(res, req)
Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str def get_cookie_header(jar, request): """ Produce an appropriate Cookie header string to be sent with `request`, or None. :rtype: str """ r = MockRequest(request) jar.add_cookie_header(r) return r.get_new_headers().get('Cookie')
Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). def remove_cookie_by_name(cookiejar, name, domain=None, path=None): """Unsets a cookie by name, by default over all domains and paths. Wraps CookieJar.clear(), is O(n). """ clearables = [] for cookie in cookiejar: if cookie.name != name: continue if domain is not None and domain != cookie.domain: continue if path is not None and path != cookie.path: continue clearables.append((cookie.domain, cookie.path, cookie.name)) for domain, path, name in clearables: cookiejar.clear(domain, path, name)
Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). def create_cookie(name, value, **kwargs): """Make a cookie from underspecified parameters. By default, the pair of `name` and `value` will be set for the domain '' and sent on every request (this is sometimes called a "supercookie"). """ result = { 'version': 0, 'name': name, 'value': value, 'port': None, 'domain': '', 'path': '/', 'secure': False, 'expires': None, 'discard': True, 'comment': None, 'comment_url': None, 'rest': {'HttpOnly': None}, 'rfc2109': False, } badargs = set(kwargs) - set(result) if badargs: err = 'create_cookie() got unexpected keyword arguments: %s' raise TypeError(err % list(badargs)) result.update(kwargs) result['port_specified'] = bool(result['port']) result['domain_specified'] = bool(result['domain']) result['domain_initial_dot'] = result['domain'].startswith('.') result['path_specified'] = bool(result['path']) return cookielib.Cookie(**result)
Convert a Morsel object into a Cookie containing the one k/v pair. def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: try: expires = int(time.time() + int(morsel['max-age'])) except ValueError: raise TypeError('max-age: %s must be integer' % morsel['max-age']) elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = calendar.timegm( time.strptime(morsel['expires'], time_template) ) return create_cookie( comment=morsel['comment'], comment_url=bool(morsel['comment']), discard=False, domain=morsel['domain'], expires=expires, name=morsel.key, path=morsel['path'], port=None, rest={'HttpOnly': morsel['httponly']}, rfc2109=False, secure=bool(morsel['secure']), value=morsel.value, version=morsel['version'] or 0, )
Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True): """Returns a CookieJar from a key/value dictionary. :param cookie_dict: Dict of key/values to insert into CookieJar. :param cookiejar: (optional) A cookiejar to add the cookies to. :param overwrite: (optional) If False, will not replace cookies already in the jar with new ones. :rtype: CookieJar """ if cookiejar is None: cookiejar = RequestsCookieJar() if cookie_dict is not None: names_from_jar = [cookie.name for cookie in cookiejar] for name in cookie_dict: if overwrite or (name not in names_from_jar): cookiejar.set_cookie(create_cookie(name, cookie_dict[name])) return cookiejar
Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar """ if not isinstance(cookiejar, cookielib.CookieJar): raise ValueError('You can only merge into CookieJar') if isinstance(cookies, dict): cookiejar = cookiejar_from_dict( cookies, cookiejar=cookiejar, overwrite=False) elif isinstance(cookies, cookielib.CookieJar): try: cookiejar.update(cookies) except AttributeError: for cookie_in_jar in cookies: cookiejar.set_cookie(cookie_in_jar) return cookiejar
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1). """ try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. def set(self, name, value, **kwargs): """Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. """ # support client code that unsets cookies by assignment of a None value: if value is None: remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c
Utility method to list all the domains in the jar. def list_domains(self): """Utility method to list all the domains in the jar.""" 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): """Utility method to list all the paths in the jar.""" 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. :rtype: bool def multiple_domains(self): """Returns True if there are multiple domains in the jar. Returns False otherwise. :rtype: bool """ 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
Updates this jar with cookies from another CookieJar or dict-like def update(self, other): """Updates this jar with cookies from another CookieJar or dict-like""" 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. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value def _find(self, name, domain=None, path=None): """Requests uses this method internally to get cookie values. If there are conflicting cookies, _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown if there are conflicting cookies. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :return: cookie.value """ 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. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value def _find_no_duplicates(self, name, domain=None, path=None): """Both ``__get_item__`` and ``get`` call this function: it's never used elsewhere in Requests. :param name: a string containing name of cookie :param domain: (optional) string containing domain of cookie :param path: (optional) string containing path of cookie :raises KeyError: if cookie is not found :raises CookieConflictError: if there are multiple cookies that match name and optionally domain and path :return: cookie.value """ 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: # if there are multiple cookies that meet passed in criteria raise CookieConflictError('There are multiple cookies with name, %r' % (name)) toReturn = cookie.value # we will eventually return this as long as no cookie conflict if toReturn: return toReturn raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
Return a copy of this RequestsCookieJar. def copy(self): """Return a copy of this RequestsCookieJar.""" new_cj = RequestsCookieJar() new_cj.set_policy(self.get_policy()) new_cj.update(self) return new_cj
This returns a number, n constrained to the min and max bounds. def constrain (n, min, max): '''This returns a number, n constrained to the min and max bounds. ''' if n < min: return min if n > max: return max return n
This converts from the external coding system (as passed to the constructor) to the internal one (unicode). def _decode(self, s): '''This converts from the external coding system (as passed to the constructor) to the internal one (unicode). ''' if self.decoder is not None: return self.decoder.decode(s) else: raise TypeError("This screen was constructed with encoding=None, " "so it does not handle bytes.")
This returns a printable representation of the screen as a unicode string (which, under Python 3.x, is the same as 'str'). The end of each screen line is terminated by a newline. def _unicode(self): '''This returns a printable representation of the screen as a unicode string (which, under Python 3.x, is the same as 'str'). The end of each screen line is terminated by a newline.''' return u'\n'.join ([ u''.join(c) for c in self.w ])
This returns a copy of the screen as a unicode string. This is similar to __str__/__unicode__ except that lines are not terminated with line feeds. def dump (self): '''This returns a copy of the screen as a unicode string. This is similar to __str__/__unicode__ except that lines are not terminated with line feeds.''' return u''.join ([ u''.join(c) for c in self.w ])
This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/__unicode__ except that it adds a box. def pretty (self): '''This returns a copy of the screen as a unicode string with an ASCII text box around the screen border. This is similar to __str__/__unicode__ except that it adds a box.''' top_bot = u'+' + u'-'*self.cols + u'+\n' return top_bot + u'\n'.join([u'|'+line+u'|' for line in unicode(self).split(u'\n')]) + u'\n' + top_bot
This moves the cursor down with scrolling. def lf (self): '''This moves the cursor down with scrolling. ''' old_r = self.cur_r self.cursor_down() if old_r == self.cur_r: self.scroll_up () self.erase_line()
Screen array starts at 1 index. def put_abs (self, r, c, ch): '''Screen array starts at 1 index.''' r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) if isinstance(ch, bytes): ch = self._decode(ch)[0] else: ch = ch[0] self.w[r-1][c-1] = ch
This puts a characters at the current cursor position. def put (self, ch): '''This puts a characters at the current cursor position. ''' if isinstance(ch, bytes): ch = self._decode(ch) self.put_abs (self.cur_r, self.cur_c, ch)
This inserts a character at (r,c). Everything under and to the right is shifted right one character. The last character of the line is lost. def insert_abs (self, r, c, ch): '''This inserts a character at (r,c). Everything under and to the right is shifted right one character. The last character of the line is lost. ''' if isinstance(ch, bytes): ch = self._decode(ch) r = constrain (r, 1, self.rows) c = constrain (c, 1, self.cols) for ci in range (self.cols, c, -1): self.put_abs (r,ci, self.get_abs(r,ci-1)) self.put_abs (r,c,ch)
This returns a list of lines representing the region. def get_region (self, rs,cs, re,ce): '''This returns a list of lines representing the region. ''' rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (ce, 1, self.cols) if rs > re: rs, re = re, rs if cs > ce: cs, ce = ce, cs sc = [] for r in range (rs, re+1): line = u'' for c in range (cs, ce + 1): ch = self.get_abs (r,c) line = line + ch sc.append (line) return sc
This keeps the cursor within the screen area. def cursor_constrain (self): '''This keeps the cursor within the screen area. ''' self.cur_r = constrain (self.cur_r, 1, self.rows) self.cur_c = constrain (self.cur_c, 1, self.cols)
Save current cursor position. def cursor_save_attrs (self): # <ESC>7 '''Save current cursor position.''' self.cur_saved_r = self.cur_r self.cur_saved_c = self.cur_c
This keeps the scroll region within the screen region. def scroll_constrain (self): '''This keeps the scroll region within the screen region.''' if self.scroll_row_start <= 0: self.scroll_row_start = 1 if self.scroll_row_end > self.rows: self.scroll_row_end = self.rows
Enable scrolling from row {start} to row {end}. def scroll_screen_rows (self, rs, re): # <ESC>[{start};{end}r '''Enable scrolling from row {start} to row {end}.''' self.scroll_row_start = rs self.scroll_row_end = re self.scroll_constrain()
Scroll display down one line. def scroll_down (self): # <ESC>D '''Scroll display down one line.''' # Screen is indexed from 1, but arrays are indexed from 0. s = self.scroll_row_start - 1 e = self.scroll_row_end - 1 self.w[s+1:e+1] = copy.deepcopy(self.w[s:e])
Erases from the current cursor position to the end of the current line. def erase_end_of_line (self): # <ESC>[0K -or- <ESC>[K '''Erases from the current cursor position to the end of the current line.''' self.fill_region (self.cur_r, self.cur_c, self.cur_r, self.cols)
Erases from the current cursor position to the start of the current line. def erase_start_of_line (self): # <ESC>[1K '''Erases from the current cursor position to the start of the current line.''' self.fill_region (self.cur_r, 1, self.cur_r, self.cur_c)
Erases the entire current line. def erase_line (self): # <ESC>[2K '''Erases the entire current line.''' self.fill_region (self.cur_r, 1, self.cur_r, self.cols)
Erases the screen from the current line down to the bottom of the screen. def erase_down (self): # <ESC>[0J -or- <ESC>[J '''Erases the screen from the current line down to the bottom of the screen.''' self.erase_end_of_line () self.fill_region (self.cur_r + 1, 1, self.rows, self.cols)
Erases the screen from the current line up to the top of the screen. def erase_up (self): # <ESC>[1J '''Erases the screen from the current line up to the top of the screen.''' self.erase_start_of_line () self.fill_region (self.cur_r-1, 1, 1, self.cols)
Pull a value from the dict and convert to int :param default_to_zero: If the value is None or empty, treat it as zero :param default: If the value is missing in the dict use this default def to_int(d, key, default_to_zero=False, default=None, required=True): """Pull a value from the dict and convert to int :param default_to_zero: If the value is None or empty, treat it as zero :param default: If the value is missing in the dict use this default """ value = d.get(key) or default if (value in ["", None]) and default_to_zero: return 0 if value is None: if required: raise ParseError("Unable to read %s from %s" % (key, d)) else: return int(value)
Parses ISO 8601 time zone specs into tzinfo offsets def parse_timezone(matches, default_timezone=UTC): """Parses ISO 8601 time zone specs into tzinfo offsets """ if matches["timezone"] == "Z": return UTC # This isn't strictly correct, but it's common to encounter dates without # timezones so I'll assume the default (which defaults to UTC). # Addresses issue 4. if matches["timezone"] is None: return default_timezone sign = matches["tz_sign"] hours = to_int(matches, "tz_hour") minutes = to_int(matches, "tz_minute", default_to_zero=True) description = "%s%02d:%02d" % (sign, hours, minutes) if sign == "-": hours = -hours minutes = -minutes return FixedOffset(hours, minutes, description)
Parses ISO 8601 dates into datetime objects The timezone is parsed from the date string. However it is quite common to have dates without a timezone (not strictly correct). In this case the default timezone specified in default_timezone is used. This is UTC by default. :param datestring: The date to parse as a string :param default_timezone: A datetime tzinfo instance to use when no timezone is specified in the datestring. If this is set to None then a naive datetime object is returned. :returns: A datetime.datetime instance :raises: ParseError when there is a problem parsing the date or constructing the datetime instance. def parse_date(datestring, default_timezone=UTC): """Parses ISO 8601 dates into datetime objects The timezone is parsed from the date string. However it is quite common to have dates without a timezone (not strictly correct). In this case the default timezone specified in default_timezone is used. This is UTC by default. :param datestring: The date to parse as a string :param default_timezone: A datetime tzinfo instance to use when no timezone is specified in the datestring. If this is set to None then a naive datetime object is returned. :returns: A datetime.datetime instance :raises: ParseError when there is a problem parsing the date or constructing the datetime instance. """ if not isinstance(datestring, _basestring): raise ParseError("Expecting a string %r" % datestring) m = ISO8601_REGEX.match(datestring) if not m: raise ParseError("Unable to parse date string %r" % datestring) groups = m.groupdict() tz = parse_timezone(groups, default_timezone=default_timezone) groups["second_fraction"] = int(Decimal("0.%s" % (groups["second_fraction"] or 0)) * Decimal("1000000.0")) try: return datetime.datetime( year=to_int(groups, "year"), month=to_int(groups, "month", default=to_int(groups, "monthdash", required=False, default=1)), day=to_int(groups, "day", default=to_int(groups, "daydash", required=False, default=1)), hour=to_int(groups, "hour", default_to_zero=True), minute=to_int(groups, "minute", default_to_zero=True), second=to_int(groups, "second", default_to_zero=True), microsecond=groups["second_fraction"], tzinfo=tz, ) except Exception as e: raise ParseError(e)
Signal handler, used to gracefully shut down the ``spinner`` instance when specified signal is received by the process running the ``spinner``. ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal`` function for more details. def default_handler(signum, frame, spinner): """Signal handler, used to gracefully shut down the ``spinner`` instance when specified signal is received by the process running the ``spinner``. ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal`` function for more details. """ spinner.fail() spinner.stop() sys.exit(0)
Signal handler, used to gracefully shut down the ``spinner`` instance when specified signal is received by the process running the ``spinner``. ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal`` function for more details. def fancy_handler(signum, frame, spinner): """Signal handler, used to gracefully shut down the ``spinner`` instance when specified signal is received by the process running the ``spinner``. ``signum`` and ``frame`` are mandatory arguments. Check ``signal.signal`` function for more details. """ spinner.red.fail("✘") spinner.stop() sys.exit(0)
Re-map the characters in the string according to UTS46 processing. def uts46_remap(domain, std3_rules=True, transitional=False): """Re-map the characters in the string according to UTS46 processing.""" from .uts46data import uts46data output = u"" try: for pos, char in enumerate(domain): code_point = ord(char) uts46row = uts46data[code_point if code_point < 256 else bisect.bisect_left(uts46data, (code_point, "Z")) - 1] status = uts46row[1] replacement = uts46row[2] if len(uts46row) == 3 else None if (status == "V" or (status == "D" and not transitional) or (status == "3" and not std3_rules and replacement is None)): output += char elif replacement is not None and (status == "M" or (status == "3" and not std3_rules) or (status == "D" and transitional)): output += replacement elif status != "I": raise IndexError() return unicodedata.normalize("NFC", output) except IndexError: raise InvalidCodepoint( "Codepoint {0} not allowed at position {1} in {2}".format( _unot(code_point), pos + 1, repr(domain)))
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == 'CPython': implementation_version = platform.python_version() elif implementation == 'PyPy': implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': implementation_version = ''.join([ implementation_version, sys.pypy_version_info.releaselevel ]) elif implementation == 'Jython': implementation_version = platform.python_version() # Complete Guess elif implementation == 'IronPython': implementation_version = platform.python_version() # Complete Guess else: implementation_version = 'Unknown' return {'name': implementation, 'version': implementation_version}
Generate information for a bug report. def info(): """Generate information for a bug report.""" try: platform_info = { 'system': platform.system(), 'release': platform.release(), } except IOError: platform_info = { 'system': 'Unknown', 'release': 'Unknown', } implementation_info = _implementation() urllib3_info = {'version': urllib3.__version__} chardet_info = {'version': chardet.__version__} pyopenssl_info = { 'version': None, 'openssl_version': '', } if OpenSSL: pyopenssl_info = { 'version': OpenSSL.__version__, 'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER, } cryptography_info = { 'version': getattr(cryptography, '__version__', ''), } idna_info = { 'version': getattr(idna, '__version__', ''), } system_ssl = ssl.OPENSSL_VERSION_NUMBER system_ssl_info = { 'version': '%x' % system_ssl if system_ssl is not None else '' } return { 'platform': platform_info, 'implementation': implementation_info, 'system_ssl': system_ssl_info, 'using_pyopenssl': pyopenssl is not None, 'pyOpenSSL': pyopenssl_info, 'urllib3': urllib3_info, 'chardet': chardet_info, 'cryptography': cryptography_info, 'idna': idna_info, 'requests': { 'version': requests_version, }, }
>>> package = yarg.get('yarg') >>> v = "0.1.0" >>> r = package.release(v) >>> r.package_type u'wheel' def package_type(self): """ >>> package = yarg.get('yarg') >>> v = "0.1.0" >>> r = package.release(v) >>> r.package_type u'wheel' """ mapping = {'bdist_egg': u'egg', 'bdist_wheel': u'wheel', 'sdist': u'source'} ptype = self._release['packagetype'] if ptype in mapping.keys(): return mapping[ptype] return ptype
Process a single character. Called by :meth:`write`. def process (self, c): """Process a single character. Called by :meth:`write`.""" if isinstance(c, bytes): c = self._decode(c) self.state.process(c)
Process text, writing it to the virtual screen while handling ANSI escape codes. def write (self, s): """Process text, writing it to the virtual screen while handling ANSI escape codes. """ if isinstance(s, bytes): s = self._decode(s) for c in s: self.process(c)
This puts a character at the current cursor position. The cursor position is moved forward with wrap-around, but no scrolling is done if the cursor hits the lower-right corner of the screen. def write_ch (self, ch): '''This puts a character at the current cursor position. The cursor position is moved forward with wrap-around, but no scrolling is done if the cursor hits the lower-right corner of the screen. ''' if isinstance(ch, bytes): ch = self._decode(ch) #\r and \n both produce a call to cr() and lf(), respectively. ch = ch[0] if ch == u'\r': self.cr() return if ch == u'\n': self.crlf() return if ch == chr(screen.BS): self.cursor_back() return self.put_abs(self.cur_r, self.cur_c, ch) old_r = self.cur_r old_c = self.cur_c self.cursor_forward() if old_c == self.cur_c: self.cursor_down() if old_r != self.cur_r: self.cursor_home (self.cur_r, 1) else: self.scroll_up () self.cursor_home (self.cur_r, 1) self.erase_line()
Returns the default stream encoding if not found. def get_best_encoding(stream): """Returns the default stream encoding if not found.""" rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding() if is_ascii_encoding(rv): return 'utf-8' return rv
Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. def get_terminal_size(fallback=(80, 24)): """Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. """ # Try the environment first try: columns = int(os.environ["COLUMNS"]) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ["LINES"]) except (KeyError, ValueError): lines = 0 # Only query if necessary if columns <= 0 or lines <= 0: try: size = _get_terminal_size(sys.__stdout__.fileno()) except (NameError, OSError): size = terminal_size(*fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return terminal_size(columns, lines)
Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ','.join(accept_encoding) else: accept_encoding = ACCEPT_ENCODING headers['accept-encoding'] = accept_encoding if user_agent: headers['user-agent'] = user_agent if keep_alive: headers['connection'] = 'keep-alive' if basic_auth: headers['authorization'] = 'Basic ' + \ b64encode(b(basic_auth)).decode('utf-8') if proxy_basic_auth: headers['proxy-authorization'] = 'Basic ' + \ b64encode(b(proxy_basic_auth)).decode('utf-8') if disable_cache: headers['cache-control'] = 'no-cache' return headers
If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. def set_file_position(body, pos): """ If a position is provided, move file to that point. Otherwise, we'll attempt to record a position for future use. """ if pos is not None: rewind_body(body, pos) elif getattr(body, 'tell', None) is not None: try: pos = body.tell() except (IOError, OSError): # This differentiates from None, allowing us to catch # a failed `tell()` later when trying to rewind the body. pos = _FAILEDTELL return pos
Attempt to rewind body to a certain position. Primarily used for request redirects and retries. :param body: File-like object that supports seek. :param int pos: Position to seek to in file. def rewind_body(body, body_pos): """ Attempt to rewind body to a certain position. Primarily used for request redirects and retries. :param body: File-like object that supports seek. :param int pos: Position to seek to in file. """ body_seek = getattr(body, 'seek', None) if body_seek is not None and isinstance(body_pos, integer_types): try: body_seek(body_pos) except (IOError, OSError): raise UnrewindableBodyError("An error occurred when rewinding request " "body for redirect/retry.") elif body_pos is _FAILEDTELL: raise UnrewindableBodyError("Unable to record file position for rewinding " "request body during a redirect/retry.") else: raise ValueError("body_pos must be of type integer, " "instead it was %s." % type(body_pos))
Deep-copy a value into JSON-safe types. def _copy_jsonsafe(value): """Deep-copy a value into JSON-safe types. """ if isinstance(value, six.string_types + (numbers.Number,)): return value if isinstance(value, collections_abc.Mapping): return {six.text_type(k): _copy_jsonsafe(v) for k, v in value.items()} if isinstance(value, collections_abc.Iterable): return [_copy_jsonsafe(v) for v in value] if value is None: # This doesn't happen often for us. return None return six.text_type(value)
Helper for clearing all the keys in a database. Use with caution! def clear(self): """Helper for clearing all the keys in a database. Use with caution!""" for key in self.conn.keys(): self.conn.delete(key)
Be aware that this treats any sequence type with the equal members as equal. As it is used to identify equality of schemas, this can be considered okay as definitions are semantically equal regardless the container type. def mapping_to_frozenset(mapping): """ Be aware that this treats any sequence type with the equal members as equal. As it is used to identify equality of schemas, this can be considered okay as definitions are semantically equal regardless the container type. """ mapping = mapping.copy() for key, value in mapping.items(): if isinstance(value, Mapping): mapping[key] = mapping_to_frozenset(value) elif isinstance(value, Sequence): value = list(value) for i, item in enumerate(value): if isinstance(item, Mapping): value[i] = mapping_to_frozenset(item) mapping[key] = tuple(value) return frozenset(mapping.items())
Dynamically create a :class:`~cerberus.Validator` subclass. Docstrings of mixin-classes will be added to the resulting class' one if ``__doc__`` is not in :obj:`namespace`. :param name: The name of the new class. :type name: :class:`str` :param bases: Class(es) with additional and overriding attributes. :type bases: :class:`tuple` of or a single :term:`class` :param namespace: Attributes for the new class. :type namespace: :class:`dict` :return: The created class. def validator_factory(name, bases=None, namespace={}): """ Dynamically create a :class:`~cerberus.Validator` subclass. Docstrings of mixin-classes will be added to the resulting class' one if ``__doc__`` is not in :obj:`namespace`. :param name: The name of the new class. :type name: :class:`str` :param bases: Class(es) with additional and overriding attributes. :type bases: :class:`tuple` of or a single :term:`class` :param namespace: Attributes for the new class. :type namespace: :class:`dict` :return: The created class. """ Validator = get_Validator_class() if bases is None: bases = (Validator,) elif isinstance(bases, tuple): bases += (Validator,) else: bases = (bases, Validator) docstrings = [x.__doc__ for x in bases if x.__doc__] if len(docstrings) > 1 and '__doc__' not in namespace: namespace.update({'__doc__': '\n'.join(docstrings)}) return type(name, bases, namespace)
Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are doubled, so they are all escaped properly. * Backslashes elsewhere are left as-is; cmd will interpret them literally. The result is then quoted into a pair of double quotes to be grouped. An argument is intentionally not quoted if it does not contain whitespaces. This is done to be compatible with Windows built-in commands that don't work well with quotes, e.g. everything with `echo`, and DOS-style (forward slash) switches. The intended use of this function is to pre-process an argument list before passing it into ``subprocess.Popen(..., shell=True)``. See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence def cmdify(self): """Encode into a cmd-executable string. This re-implements CreateProcess's quoting logic to turn a list of arguments into one single string for the shell to interpret. * All double quotes are escaped with a backslash. * Existing backslashes before a quote are doubled, so they are all escaped properly. * Backslashes elsewhere are left as-is; cmd will interpret them literally. The result is then quoted into a pair of double quotes to be grouped. An argument is intentionally not quoted if it does not contain whitespaces. This is done to be compatible with Windows built-in commands that don't work well with quotes, e.g. everything with `echo`, and DOS-style (forward slash) switches. The intended use of this function is to pre-process an argument list before passing it into ``subprocess.Popen(..., shell=True)``. See also: https://docs.python.org/3/library/subprocess.html#converting-argument-sequence """ return " ".join( itertools.chain( [_quote_if_contains(self.command, r"[\s^()]")], (_quote_if_contains(arg, r"[\s^]") for arg in self.args), ) )
Returns a tuple of `frozenset`s of classes and attributes. def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cls for cls in what if isclass(cls)), frozenset(cls for cls in what if isinstance(cls, Attribute)), )
Whitelist *what*. :param what: What to whitelist. :type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s :rtype: :class:`callable` def include(*what): """ Whitelist *what*. :param what: What to whitelist. :type what: :class:`list` of :class:`type` or :class:`attr.Attribute`\\ s :rtype: :class:`callable` """ cls, attrs = _split_what(what) def include_(attribute, value): return value.__class__ in cls or attribute in attrs return include_
Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable` def exclude(*what): """ Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute`\\ s. :rtype: :class:`callable` """ cls, attrs = _split_what(what) def exclude_(attribute, value): return value.__class__ not in cls and attribute not in attrs return exclude_
Return the ``attrs`` attribute values of *inst* as a dict. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the :class:`attr.Attribute` as the first argument and the value as the second argument. :param callable dict_factory: A callable to produce dictionaries from. For example, to produce ordered dictionaries instead of normal Python dictionaries, pass in ``collections.OrderedDict``. :param bool retain_collection_types: Do not convert to ``list`` when encountering an attribute whose type is ``tuple`` or ``set``. Only meaningful if ``recurse`` is ``True``. :rtype: return type of *dict_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.0.0 *dict_factory* .. versionadded:: 16.1.0 *retain_collection_types* def asdict( inst, recurse=True, filter=None, dict_factory=dict, retain_collection_types=False, ): """ Return the ``attrs`` attribute values of *inst* as a dict. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the :class:`attr.Attribute` as the first argument and the value as the second argument. :param callable dict_factory: A callable to produce dictionaries from. For example, to produce ordered dictionaries instead of normal Python dictionaries, pass in ``collections.OrderedDict``. :param bool retain_collection_types: Do not convert to ``list`` when encountering an attribute whose type is ``tuple`` or ``set``. Only meaningful if ``recurse`` is ``True``. :rtype: return type of *dict_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.0.0 *dict_factory* .. versionadded:: 16.1.0 *retain_collection_types* """ attrs = fields(inst.__class__) rv = dict_factory() for a in attrs: v = getattr(inst, a.name) if filter is not None and not filter(a, v): continue if recurse is True: if has(v.__class__): rv[a.name] = asdict( v, True, filter, dict_factory, retain_collection_types ) elif isinstance(v, (tuple, list, set)): cf = v.__class__ if retain_collection_types is True else list rv[a.name] = cf( [ _asdict_anything( i, filter, dict_factory, retain_collection_types ) for i in v ] ) elif isinstance(v, dict): df = dict_factory rv[a.name] = df( ( _asdict_anything( kk, filter, df, retain_collection_types ), _asdict_anything( vv, filter, df, retain_collection_types ), ) for kk, vv in iteritems(v) ) else: rv[a.name] = v else: rv[a.name] = v return rv
``asdict`` only works on attrs instances, this works on anything. def _asdict_anything(val, filter, dict_factory, retain_collection_types): """ ``asdict`` only works on attrs instances, this works on anything. """ if getattr(val.__class__, "__attrs_attrs__", None) is not None: # Attrs class. rv = asdict(val, True, filter, dict_factory, retain_collection_types) elif isinstance(val, (tuple, list, set)): cf = val.__class__ if retain_collection_types is True else list rv = cf( [ _asdict_anything( i, filter, dict_factory, retain_collection_types ) for i in val ] ) elif isinstance(val, dict): df = dict_factory rv = df( ( _asdict_anything(kk, filter, df, retain_collection_types), _asdict_anything(vv, filter, df, retain_collection_types), ) for kk, vv in iteritems(val) ) else: rv = val return rv
Return the ``attrs`` attribute values of *inst* as a tuple. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the :class:`attr.Attribute` as the first argument and the value as the second argument. :param callable tuple_factory: A callable to produce tuples from. For example, to produce lists instead of tuples. :param bool retain_collection_types: Do not convert to ``list`` or ``dict`` when encountering an attribute which type is ``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is ``True``. :rtype: return type of *tuple_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.2.0 def astuple( inst, recurse=True, filter=None, tuple_factory=tuple, retain_collection_types=False, ): """ Return the ``attrs`` attribute values of *inst* as a tuple. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of an ``attrs``-decorated class. :param bool recurse: Recurse into classes that are also ``attrs``-decorated. :param callable filter: A callable whose return code determines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the :class:`attr.Attribute` as the first argument and the value as the second argument. :param callable tuple_factory: A callable to produce tuples from. For example, to produce lists instead of tuples. :param bool retain_collection_types: Do not convert to ``list`` or ``dict`` when encountering an attribute which type is ``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is ``True``. :rtype: return type of *tuple_factory* :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 16.2.0 """ attrs = fields(inst.__class__) rv = [] retain = retain_collection_types # Very long. :/ for a in attrs: v = getattr(inst, a.name) if filter is not None and not filter(a, v): continue if recurse is True: if has(v.__class__): rv.append( astuple( v, recurse=True, filter=filter, tuple_factory=tuple_factory, retain_collection_types=retain, ) ) elif isinstance(v, (tuple, list, set)): cf = v.__class__ if retain is True else list rv.append( cf( [ astuple( j, recurse=True, filter=filter, tuple_factory=tuple_factory, retain_collection_types=retain, ) if has(j.__class__) else j for j in v ] ) ) elif isinstance(v, dict): df = v.__class__ if retain is True else dict rv.append( df( ( astuple( kk, tuple_factory=tuple_factory, retain_collection_types=retain, ) if has(kk.__class__) else kk, astuple( vv, tuple_factory=tuple_factory, retain_collection_types=retain, ) if has(vv.__class__) else vv, ) for kk, vv in iteritems(v) ) ) else: rv.append(v) else: rv.append(v) return rv if tuple_factory is list else tuple_factory(rv)
Copy *inst* and apply *changes*. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. :raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't be found on *cls*. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. deprecated:: 17.1.0 Use :func:`evolve` instead. def assoc(inst, **changes): """ Copy *inst* and apply *changes*. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. :raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't be found on *cls*. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. deprecated:: 17.1.0 Use :func:`evolve` instead. """ import warnings warnings.warn( "assoc is deprecated and will be removed after 2018/01.", DeprecationWarning, stacklevel=2, ) new = copy.copy(inst) attrs = fields(inst.__class__) for k, v in iteritems(changes): a = getattr(attrs, k, NOTHING) if a is NOTHING: raise AttrsAttributeNotFoundError( "{k} is not an attrs attribute on {cl}.".format( k=k, cl=new.__class__ ) ) _obj_setattr(new, k, v) return new
Create a new instance, based on *inst* with *changes* applied. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. :raise TypeError: If *attr_name* couldn't be found in the class ``__init__``. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 17.1.0 def evolve(inst, **changes): """ Create a new instance, based on *inst* with *changes* applied. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. :raise TypeError: If *attr_name* couldn't be found in the class ``__init__``. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. .. versionadded:: 17.1.0 """ cls = inst.__class__ attrs = fields(cls) for a in attrs: if not a.init: continue attr_name = a.name # To deal with private attributes. init_name = attr_name if attr_name[0] != "_" else attr_name[1:] if init_name not in changes: changes[init_name] = getattr(inst, attr_name) return cls(**changes)
Constructs a request to the PyPI server and returns a :class:`yarg.package.Package`. :param package_name: case sensitive name of the package on the PyPI server. :param pypi_server: (option) URL to the PyPI server. >>> import yarg >>> package = yarg.get('yarg') <Package yarg> def get(package_name, pypi_server="https://pypi.python.org/pypi/"): """ Constructs a request to the PyPI server and returns a :class:`yarg.package.Package`. :param package_name: case sensitive name of the package on the PyPI server. :param pypi_server: (option) URL to the PyPI server. >>> import yarg >>> package = yarg.get('yarg') <Package yarg> """ if not pypi_server.endswith("/"): pypi_server = pypi_server + "/" response = requests.get("{0}{1}/json".format(pypi_server, package_name)) if response.status_code >= 300: raise HTTPError(status_code=response.status_code, reason=response.reason) if hasattr(response.content, 'decode'): return json2package(response.content.decode()) else: return json2package(response.content)
Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed def resolve_ctx(cli, prog_name, args): """ Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed """ ctx = cli.make_context(prog_name, args, resilient_parsing=True) args = ctx.protected_args + ctx.args while args: if isinstance(ctx.command, MultiCommand): if not ctx.command.chain: cmd_name, cmd, args = ctx.command.resolve_command(ctx, args) if cmd is None: return ctx ctx = cmd.make_context(cmd_name, args, parent=ctx, resilient_parsing=True) args = ctx.protected_args + ctx.args else: # Walk chained subcommand contexts saving the last one. while args: cmd_name, cmd, args = ctx.command.resolve_command(ctx, args) if cmd is None: return ctx sub_ctx = cmd.make_context(cmd_name, args, parent=ctx, allow_extra_args=True, allow_interspersed_args=False, resilient_parsing=True) args = sub_ctx.args ctx = sub_ctx args = sub_ctx.protected_args + sub_ctx.args else: break return ctx
:param all_args: the full original list of args supplied :param cmd_param: the current command paramter :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values def is_incomplete_option(all_args, cmd_param): """ :param all_args: the full original list of args supplied :param cmd_param: the current command paramter :return: whether or not the last option declaration (i.e. starts "-" or "--") is incomplete and corresponds to this cmd_param. In other words whether this cmd_param option can still accept values """ if not isinstance(cmd_param, Option): return False if cmd_param.is_flag: return False last_option = None for index, arg_str in enumerate(reversed([arg for arg in all_args if arg != WORDBREAK])): if index + 1 > cmd_param.nargs: break if start_of_option(arg_str): last_option = arg_str return True if last_option and last_option in cmd_param.opts else False