text
stringlengths
81
112k
Build a response by making a request or using the cache. This will end up calling send and returning a potentially cached response def build_response( self, request, response, from_cache=False, cacheable_methods=None ): """ Build a response by making a request or using the ...
Try to look up the process tree via Linux's /proc def get_process_mapping(): """Try to look up the process tree via Linux's /proc """ with open('/proc/{0}/stat'.format(os.getpid())) as f: self_tty = f.read().split()[STAT_TTY] processes = {} for pid in os.listdir('/proc'): if not pid...
Return (hash, length) for path using hashlib.sha256() def rehash(path, blocksize=1 << 20): # type: (str, int) -> Tuple[str, str] """Return (hash, length) for path using hashlib.sha256()""" h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize...
Replace the Python tag in a wheel file name with a new value. def replace_python_tag(wheelname, new_tag): # type: (str, str) -> str """Replace the Python tag in a wheel file name with a new value. """ parts = wheelname.split('-') parts[-3] = new_tag return '-'.join(parts)
Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. ...
Return the given rows of a RECORD file in sorted order. Each row is a 3-tuple (path, hash, size) and corresponds to a record of a RECORD file (see PEP 376 and PEP 427 for details). For the rows passed to this function, the size can be an integer as an int or string, or the empty string. def sorted_ou...
:param installed: A map from archive RECORD path to installation RECORD path. def get_csv_rows_for_installed( old_csv_rows, # type: Iterable[List[str]] installed, # type: Dict[str, str] changed, # type: set generated, # type: List[str] lib_dir, # type: str ): # type: (...) -> List[...
Install a wheel def move_wheel_files( name, # type: str req, # type: Requirement wheeldir, # type: str user=False, # type: bool home=None, # type: Optional[str] root=None, # type: Optional[str] pycompile=True, # type: bool scheme=None, # type: Optional[Mapping[str, str]] iso...
Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we couldn't parse / extract it. def wheel_version(source_dir): # type: (Optional[str]) -> Optional[Tuple[int, ...]] """ Return the Wheel-Version of an extracted wheel, if possible. Otherwise, return None if we ...
Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 ""...
Return whether to build an InstallRequirement object using the ephemeral cache. :param cache_available: whether a cache directory is available for the autobuilding=True case. :return: True or False to build the requirement with ephem_cache=True or False, respectively; or None not to build ...
Format command information for logging. def format_command( command_args, # type: List[str] command_output, # type: str ): # type: (...) -> str """ Format command information for logging. """ text = 'Command arguments: {}\n'.format(command_args) if not command_output: text +=...
Return the path to the wheel in the temporary build directory. def get_legacy_build_wheel_path( names, # type: List[str] temp_dir, # type: str req, # type: InstallRequirement command_args, # type: List[str] command_output, # type: str ): # type: (...) -> Optional[str] """ Return th...
Return the lowest index that one of the wheel's file_tag combinations achieves in the supported_tags list e.g. if there are 8 supported tags, and one of the file tags is first in the list, then return 0. Returns None is the wheel is not supported. def support_index_min(self, tags=None): ...
Is this wheel supported on this system? def supported(self, tags=None): # type: (Optional[List[Pep425Tag]]) -> bool """Is this wheel supported on this system?""" if tags is None: # for mock tags = pep425tags.get_supported() return bool(set(tags).intersection(self.file_tags)...
Build one wheel. :return: The filename of the built wheel, or None if the build failed. def _build_one(self, req, output_dir, python_tag=None): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ # Install build deps into temporary di...
Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully built. Otherwise, returns None. def _build_one_pep517(self, req, tempd, python_tag=None): """Build one InstallRequirement using the PEP 517 build process. Returns path to wheel if successfully ...
Build one InstallRequirement using the "legacy" build process. Returns path to wheel if successfully built. Otherwise, returns None. def _build_one_legacy(self, req, tempd, python_tag=None): """Build one InstallRequirement using the "legacy" build process. Returns path to wheel if successfull...
Build wheels. :param unpack: If True, replace the sdist we built from with the newly built wheel, in preparation for installation. :return: True if all the wheels built correctly. def build( self, requirements, # type: Iterable[InstallRequirement] session, # type:...
Get the distutils command for interacting with PyPI configurations. :return: the command. def _get_pypirc_command(self): """ Get the distutils command for interacting with PyPI configurations. :return: the command. """ from distutils.core import Distribution from...
Read the PyPI access configuration as supported by distutils, getting PyPI to do the actual work. This populates ``username``, ``password``, ``realm`` and ``url`` attributes from the configuration. def read_configuration(self): """ Read the PyPI access configuration as supported by dist...
Save the PyPI access configuration. You must have set ``username`` and ``password`` attributes before calling this method. Again, distutils is used to do the actual work. def save_configuration(self): """ Save the PyPI access configuration. You must have set ``username`` and ``...
Check that ``username`` and ``password`` have been set, and raise an exception if not. def check_credentials(self): """ Check that ``username`` and ``password`` have been set, and raise an exception if not. """ if self.username is None or self.password is None: ...
Register a distribution on PyPI, using the provided metadata. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the distribution to be registered. :return: The HTTP response received from PyPI upon submission ...
Thread runner for reading lines of from a subprocess into a buffer. :param name: The logical name of the stream (used for logging only). :param stream: The stream to read from. This will typically a pipe connected to the output stream of a subprocess. :param outbuf: The l...
Return a suitable command for signing a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param keystor...
Run a command in a child process , passing it any input data specified. :param cmd: The command to run. :param input_data: If specified, this must be a byte string containing data to be sent to the child process. :return: A tuple consisting of the subprocess' exit cod...
Sign a file. :param filename: The pathname to the file to be signed. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param keystore: The path to a directory which ...
Upload documentation to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the documentation to be uploaded. :param doc_dir: The pathname of the directory which contains the d...
Return a suitable command for verifying a file. :param signature_filename: The pathname to the file containing the signature. :param data_filename: The pathname to the file containing the signed data. :param keystore: The path to ...
Verify a signature for a file. :param signature_filename: The pathname to the file containing the signature. :param data_filename: The pathname to the file containing the signed data. :param keystore: The path to a directory which...
This is a convenience method for downloading a file from an URL. Normally, this will be a file from the index, though currently no check is made for this (i.e. a file can be downloaded from anywhere). The method is just like the :func:`urlretrieve` function in the standard libra...
Send a standard library :class:`Request` to PyPI and return its response. :param req: The request to send. :return: The HTTP response from PyPI (a standard library HTTPResponse). def send_request(self, req): """ Send a standard library :class:`Request` to PyPI and return its ...
Encode fields and files for posting to an HTTP server. :param fields: The fields to send as a list of (fieldname, value) tuples. :param files: The files to send as a list of (fieldname, filename, file_bytes) tuple. def encode_request(self, fields, files): ...
Do the completion for bash Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False otherwise def do_bash_complete(cli, pro...
Do the fish completion Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False otherwise def do_fish_complete(cli, prog_na...
Do the powershell completion Parameters ---------- cli : click.Command The main click Command of the program prog_name : str The program name on the command line Returns ------- bool True if the completion was successful, False otherwise def do_powershell_complete(...
Returns the completion code to be evaluated by the shell Parameters ---------- shell : Shell The shell type (Default value = None) prog_name : str The program name on the command line (Default value = None) env_name : str The environment variable used to control the completi...
Install the completion Parameters ---------- shell : Shell The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None) prog_name : str The program name on the command line. It will be automatically computed if the value is None (...
Get a TreeBuilder class for various types of trees with built-in support :arg treeType: the name of the tree type required (case-insensitive). Supported values are: * "dom" - A generic builder for DOM implementations, defaulting to a xml.dom.minidom based implementation. * "etree...
Our embarrassingly-simple replacement for mimetools.choose_boundary. def choose_boundary(): """ Our embarrassingly-simple replacement for mimetools.choose_boundary. """ boundary = binascii.hexlify(os.urandom(16)) if six.PY3: boundary = boundary.decode('ascii') return boundary
Iterate over fields. Supports list of (k, v) tuples and dicts, and lists of :class:`~urllib3.fields.RequestField`. def iter_field_objects(fields): """ Iterate over fields. Supports list of (k, v) tuples and dicts, and lists of :class:`~urllib3.fields.RequestField`. """ if isinstance(...
.. deprecated:: 1.6 Iterate over fields. The addition of :class:`~urllib3.fields.RequestField` makes this function obsolete. Instead, use :func:`iter_field_objects`, which returns :class:`~urllib3.fields.RequestField` objects. Supports list of (k, v) tuples and dicts. def iter_fields(fields): ...
Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`urllib3.filepost.choose_bou...
Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for the package. def finder(package): """ Return a resource finder for a package. :param package: The name of the package. :return: A :class:`ResourceFinder` instance for...
Return a resource finder for a path, which should represent a container. :param path: The path. :return: A :class:`ResourceFinder` instance for the path. def finder_for_path(path): """ Return a resource finder for a path, which should represent a container. :param path: The path. :return: A :...
Get a resource into the cache, :param resource: A :class:`Resource` instance. :return: The pathname of the resource in the cache. def get(self, resource): """ Get a resource into the cache, :param resource: A :class:`Resource` instance. :return: The pathname of the res...
Call SAX-like content handler based on treewalker walker :arg walker: the treewalker to use to walk the tree to convert it :arg handler: SAX handler to use def to_sax(walker, handler): """Call SAX-like content handler based on treewalker walker :arg walker: the treewalker to use to walk the tree to ...
Decorator function that instantiates the Retrying object @param *dargs: positional arguments passed to Retrying object @param **dkw: keyword arguments passed to the Retrying object def retry(*dargs, **dkw): """ Decorator function that instantiates the Retrying object @param *dargs: positional argum...
Sleep a random amount of time between wait_random_min and wait_random_max def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """Sleep a random amount of time between wait_random_min and wait_random_max""" return random.randint(self._wait_random_min, self._wait_random_max)
Sleep an incremental amount of time after each attempt, starting at wait_incrementing_start and incrementing by wait_incrementing_increment def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): """ Sleep an incremental amount of time after each attempt, starting a...
Return the return value of this Attempt instance or raise an Exception. If wrap_exception is true, this Attempt is wrapped inside of a RetryError before being raised. def get(self, wrap_exception=False): """ Return the return value of this Attempt instance or raise an Exception. ...
A range that can't generate ranges with a length of more than MAX_RANGE items. def safe_range(*args): """A range that can't generate ranges with a length of more than MAX_RANGE items. """ rng = range(*args) if len(rng) > MAX_RANGE: raise OverflowError('range too big, maximum size for ra...
Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_att...
This function checks if an attribute on a builtin mutable object (list, dict, set or deque) would modify it if called. It also supports the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and with Python 2.6 onwards the abstract base classes `MutableSet`, `MutableMapping`, and `MutableSe...
The sandboxed environment will call this method to check if the attribute of an object is safe to access. Per default all attributes starting with an underscore are considered private as well as the special attributes of internal python objects as returned by the :func:`is_internal_attr...
For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 def call_binop(self, context, operator, left, right): """For intercepted...
Subscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring. def getattr(self, obj, attribute): """Subscribe an object from sandboxed code and prefer the attribute. The attribute passed *must* be a bytestring. """ try: ...
Return an undefined object for unsafe attributes. def unsafe_undefined(self, obj, attribute): """Return an undefined object for unsafe attributes.""" return self.undefined('access to attribute %r of %r ' 'object is unsafe.' % ( attribute, obj.__clas...
If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. def format_string(self, s, args, kwargs): """If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. """ ...
Call an object from sandboxed code. def call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" fmt = inspect_format_method(__obj) if fmt is not None: return __self.format_string(fmt, args, kwargs) # the double prefixes are to avoid double...
Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with :func:`attr.s`! :param default: A value that is used if an ``attrs``-generated ``__init__`` is used and no value is passed while instantiating or the attribute is ex...
Create a tuple subclass to hold `Attribute`s for an `attrs` class. The subclass is a bare tuple with properties for names. class MyClassAttributes(tuple): __slots__ = () x = property(itemgetter(0)) def _make_attr_tuple_class(cls_name, attr_names): """ Create a tuple subclass to hold `...
Get annotations for *cls*. def _get_annotations(cls): """ Get annotations for *cls*. """ anns = getattr(cls, "__annotations__", None) if anns is None: return {} # Verify that the annotations aren't merely inherited. for base_cls in cls.__mro__[1:]: if anns is getattr(base_c...
Transform all `_CountingAttr`s on a class into `Attribute`s. If *these* is passed, use that and don't look for them on the class. Return an `_Attributes`. def _transform_attrs(cls, these, auto_attribs, kw_only): """ Transform all `_CountingAttr`s on a class into `Attribute`s. If *these* is passe...
r""" A class decorator that adds `dunder <https://wiki.python.org/moin/DunderAlias>`_\ -methods according to the specified attributes using :func:`attr.ib` or the *these* argument. :param these: A dictionary of name to :func:`attr.ib` mappings. This is useful to avoid the definition of your at...
Create a tuple of all values of *obj*'s *attrs*. def _attrs_to_tuple(obj, attrs): """ Create a tuple of all values of *obj*'s *attrs*. """ return tuple(getattr(obj, a.name) for a in attrs)
Add a hash method to *cls*. def _add_hash(cls, attrs): """ Add a hash method to *cls*. """ cls.__hash__ = _make_hash(attrs, frozen=False, cache_hash=False) return cls
Add comparison methods to *cls*. def _add_cmp(cls, attrs=None): """ Add comparison methods to *cls*. """ if attrs is None: attrs = cls.__attrs_attrs__ cls.__eq__, cls.__ne__, cls.__lt__, cls.__le__, cls.__gt__, cls.__ge__ = _make_cmp( # noqa attrs ) return cls
Make a repr method for *attr_names* adding *ns* to the full name. def _make_repr(attrs, ns): """ Make a repr method for *attr_names* adding *ns* to the full name. """ attr_names = tuple(a.name for a in attrs if a.repr) def __repr__(self): """ Automatically created by attrs. ...
Add a repr method to *cls*. def _add_repr(cls, ns=None, attrs=None): """ Add a repr method to *cls*. """ if attrs is None: attrs = cls.__attrs_attrs__ cls.__repr__ = _make_repr(attrs, ns) return cls
Return the tuple of ``attrs`` attributes for a class. The tuple also allows accessing the fields by their names (see below for examples). :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` ...
Return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names. :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. :rtype: an ordered dict w...
Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. def validate(inst): """ Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a clas...
Return a script of an initializer for *attrs* and a dict of globals. The globals are expected by the generated script. If *frozen* is True, we cannot set the attributes directly so we use a cached ``object.__setattr__``. def _attrs_to_init_script( attrs, frozen, slots, post_init, cache_hash, base_att...
A quick way to create a new class called *name* with *attrs*. :param name: The name for the new class. :type name: str :param attrs: A list of names or a dictionary of mappings of names to attributes. If *attrs* is a list or an ordered dict (:class:`dict` on Python 3.6+, :class:`c...
A validator that composes multiple validators into one. When called on a value, it runs all wrapped validators. :param validators: Arbitrary number of validators. :type validators: callables .. versionadded:: 17.1.0 def and_(*validators): """ A validator that composes multiple validators int...
Apply accumulated methods and return the class. def _patch_original_class(self): """ Apply accumulated methods and return the class. """ cls = self._cls base_names = self._base_names # Clean class of attribute definitions (`attr.ib()`s). if self._delete_attribs:...
Build and return a new class with a `__slots__` attribute. def _create_slots_class(self): """ Build and return a new class with a `__slots__` attribute. """ base_names = self._base_names cd = { k: v for k, v in iteritems(self._cls_dict) if k n...
Add __module__ and __qualname__ to a *method* if possible. def _add_method_dunders(self, method): """ Add __module__ and __qualname__ to a *method* if possible. """ try: method.__module__ = self._cls.__module__ except AttributeError: pass try: ...
Copy *self* and apply *changes*. def _assoc(self, **changes): """ Copy *self* and apply *changes*. """ new = copy.copy(self) new._setattrs(changes.items()) return new
Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 def validator(self, meth): """ Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 """ if sel...
Decorator that allows to set the default for an attribute. Returns *meth* unchanged. :raises DefaultAlreadySetError: If default has been set before. .. versionadded:: 17.1.0 def default(self, meth): """ Decorator that allows to set the default for an attribute. Retur...
Parses command strings and returns a Popen-ready list. def _expand_args(command): """Parses command strings and returns a Popen-ready list.""" # Prepare arguments. if isinstance(command, STR_TYPES): if sys.version_info[0] == 2: splitter = shlex.shlex(command.encode("utf-8")) el...
Std/out output (cached) def out(self): """Std/out output (cached)""" if self.__out is not None: return self.__out if self._uses_subprocess: self.__out = self.std_out.read() else: self.__out = self._pexpect_out return self.__out
Waits on the given pattern to appear in std_out def expect(self, pattern, timeout=-1): """Waits on the given pattern to appear in std_out""" if self.blocking: raise RuntimeError("expect can only be used on non-blocking commands.") try: self.subprocess.expect(pattern=pa...
Blocks until process is complete. def block(self): """Blocks until process is complete.""" if self._uses_subprocess: # consume stdout and stderr if self.blocking: try: stdout, stderr = self.subprocess.communicate() self.__o...
Runs the current command and passes its output to the next given process. def pipe(self, command, timeout=None, cwd=None): """Runs the current command and passes its output to the next given process. """ if not timeout: timeout = self.timeout if not self.was...
Backport of ``socket.makefile`` from Python 3.5. def backport_makefile(self, mode="r", buffering=None, encoding=None, errors=None, newline=None): """ Backport of ``socket.makefile`` from Python 3.5. """ if not set(mode) <= {"r", "w", "b"}: raise ValueError( "in...
Creates a processed traceback object from the exc_info. def make_traceback(exc_info, source_hint=None): """Creates a processed traceback object from the exc_info.""" exc_type, exc_value, tb = exc_info if isinstance(exc_value, TemplateSyntaxError): exc_info = translate_syntax_error(exc_value, source...
Rewrites a syntax error to please traceback systems. def translate_syntax_error(error, source=None): """Rewrites a syntax error to please traceback systems.""" error.source = source error.translated = True exc_info = (error.__class__, error, None) filename = error.filename if filename is None: ...
Return a string with the traceback. def render_as_text(self, limit=None): """Return a string with the traceback.""" lines = traceback.format_exception(self.exc_type, self.exc_value, self.frames[0], limit=limit) return ''.join(lines).rstrip()
Return a unicode string with the traceback as rendered HTML. def render_as_html(self, full=False): """Return a unicode string with the traceback as rendered HTML.""" from jinja2.debugrenderer import render_traceback return u'%s\n\n<!--\n%s\n-->' % ( render_traceback(self, full=full)...
Standard python exc_info for re-raising def standard_exc_info(self): """Standard python exc_info for re-raising""" tb = self.frames[0] # the frame will be an actual traceback (or transparent proxy) if # we are on pypy or a python implementation with support for tproxy if type(tb...
Overrides clicks ``resolve_command`` method and appends *Did you mean ...* suggestions to the raised exception message. def resolve_command(self, ctx, args): """ Overrides clicks ``resolve_command`` method and appends *Did you mean ...* suggestions to the raised exceptio...
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 ...
Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. def make_abstract_dist(req): # type: (InstallRequirement) -> DistAbstraction """Factory ...
Prepare a requirement that would be obtained from req.link def prepare_linked_requirement( self, req, # type: InstallRequirement session, # type: PipSession finder, # type: PackageFinder upgrade_allowed, # type: bool require_hashes # type: bool ): # type...
Prepare an editable requirement def prepare_editable_requirement( self, req, # type: InstallRequirement require_hashes, # type: bool use_user_site, # type: bool finder # type: PackageFinder ): # type: (...) -> DistAbstraction """Prepare an editable requir...
Prepare an already-installed requirement def prepare_installed_requirement(self, req, require_hashes, skip_reason): # type: (InstallRequirement, bool, Optional[str]) -> DistAbstraction """Prepare an already-installed requirement """ assert req.satisfied_by, "req should have been satisfi...