INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Remove the tag but not its children or text. The children and text are merged into the parent.
def drop_tag(self): """ Remove the tag, but not its children or text. The children and text are merged into the parent. Example:: >>> h = fragment_fromstring('<div>Hello <b>World!</b></div>') >>> h.find('.//b').drop_tag() >>> print(tostring(h, encoding='unicode')) <div>Hello World!</div> """ parent = self.getparent() assert parent is not None previous = self.getprevious() if self.text and isinstance(self.tag, basestring): # not a Comment, etc. if previous is None: parent.text = (parent.text or '') + self.text else: previous.tail = (previous.tail or '') + self.text if self.tail: if len(self): last = self[-1] last.tail = (last.tail or '') + self.tail elif previous is None: parent.text = (parent.text or '') + self.tail else: previous.tail = (previous.tail or '') + self.tail index = parent.index(self) parent[index:index+1] = self[:]
Find any links like <a rel = { rel } >... </ a > ; returns a list of elements.
def find_rel_links(self, rel): """ Find any links like ``<a rel="{rel}">...</a>``; returns a list of elements. """ rel = rel.lower() return [el for el in _rel_links_xpath(self) if el.get('rel').lower() == rel]
Get the first element in a document with the given id. If none is found return the default argument if provided or raise KeyError otherwise.
def get_element_by_id(self, id, *default): """ Get the first element in a document with the given id. If none is found, return the default argument if provided or raise KeyError otherwise. Note that there can be more than one element with the same id, and this isn't uncommon in HTML documents found in the wild. Browsers return only the first match, and this function does the same. """ try: # FIXME: should this check for multiple matches? # browsers just return the first one return _id_xpath(self, id=id)[0] except IndexError: if default: return default[0] else: raise KeyError(id)
Run the CSS expression on this element and its children returning a list of the results.
def cssselect(self, expr, translator='html'): """ Run the CSS expression on this element and its children, returning a list of the results. Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self) -- note that pre-compiling the expression can provide a substantial speedup. """ # Do the import here to make the dependency optional. from lxml.cssselect import CSSSelector return CSSSelector(expr, translator=translator)(self)
Make all links in the document absolute given the base_url for the document ( the full URL where the document came from ) or if no base_url is given then the. base_url of the document.
def make_links_absolute(self, base_url=None, resolve_base_href=True, handle_failures=None): """ Make all links in the document absolute, given the ``base_url`` for the document (the full URL where the document came from), or if no ``base_url`` is given, then the ``.base_url`` of the document. If ``resolve_base_href`` is true, then any ``<base href>`` tags in the document are used *and* removed from the document. If it is false then any such tag is ignored. If ``handle_failures`` is None (default), a failure to process a URL will abort the processing. If set to 'ignore', errors are ignored. If set to 'discard', failing URLs will be removed. """ if base_url is None: base_url = self.base_url if base_url is None: raise TypeError( "No base_url given, and the document has no base_url") if resolve_base_href: self.resolve_base_href() if handle_failures == 'ignore': def link_repl(href): try: return urljoin(base_url, href) except ValueError: return href elif handle_failures == 'discard': def link_repl(href): try: return urljoin(base_url, href) except ValueError: return None elif handle_failures is None: def link_repl(href): return urljoin(base_url, href) else: raise ValueError( "unexpected value for handle_failures: %r" % handle_failures) self.rewrite_links(link_repl)
Find any <base href > tag in the document and apply its values to all links found in the document. Also remove the tag once it has been applied.
def resolve_base_href(self, handle_failures=None): """ Find any ``<base href>`` tag in the document, and apply its values to all links found in the document. Also remove the tag once it has been applied. If ``handle_failures`` is None (default), a failure to process a URL will abort the processing. If set to 'ignore', errors are ignored. If set to 'discard', failing URLs will be removed. """ base_href = None basetags = self.xpath('//base[@href]|//x:base[@href]', namespaces={'x': XHTML_NAMESPACE}) for b in basetags: base_href = b.get('href') b.drop_tree() if not base_href: return self.make_links_absolute(base_href, resolve_base_href=False, handle_failures=handle_failures)
Yield ( element attribute link pos ) where attribute may be None ( indicating the link is in the text ). pos is the position where the link occurs ; often 0 but sometimes something else in the case of links in stylesheets or style tags.
def iterlinks(self): """ Yield (element, attribute, link, pos), where attribute may be None (indicating the link is in the text). ``pos`` is the position where the link occurs; often 0, but sometimes something else in the case of links in stylesheets or style tags. Note: <base href> is *not* taken into account in any way. The link you get is exactly the link in the document. Note: multiple links inside of a single text string or attribute value are returned in reversed order. This makes it possible to replace or delete them from the text string value based on their reported text positions. Otherwise, a modification at one text position can change the positions of links reported later on. """ link_attrs = defs.link_attrs for el in self.iter(etree.Element): attribs = el.attrib tag = _nons(el.tag) if tag == 'object': codebase = None ## <object> tags have attributes that are relative to ## codebase if 'codebase' in attribs: codebase = el.get('codebase') yield (el, 'codebase', codebase, 0) for attrib in ('classid', 'data'): if attrib in attribs: value = el.get(attrib) if codebase is not None: value = urljoin(codebase, value) yield (el, attrib, value, 0) if 'archive' in attribs: for match in _archive_re.finditer(el.get('archive')): value = match.group(0) if codebase is not None: value = urljoin(codebase, value) yield (el, 'archive', value, match.start()) else: for attrib in link_attrs: if attrib in attribs: yield (el, attrib, attribs[attrib], 0) if tag == 'meta': http_equiv = attribs.get('http-equiv', '').lower() if http_equiv == 'refresh': content = attribs.get('content', '') match = _parse_meta_refresh_url(content) url = (match.group('url') if match else content).strip() # unexpected content means the redirect won't work, but we might # as well be permissive and return the entire string. if url: url, pos = _unquote_match( url, match.start('url') if match else content.find(url)) yield (el, 'content', url, pos) elif tag == 'param': valuetype = el.get('valuetype') or '' if valuetype.lower() == 'ref': ## FIXME: while it's fine we *find* this link, ## according to the spec we aren't supposed to ## actually change the value, including resolving ## it. It can also still be a link, even if it ## doesn't have a valuetype="ref" (which seems to be the norm) ## http://www.w3.org/TR/html401/struct/objects.html#adef-valuetype yield (el, 'value', el.get('value'), 0) elif tag == 'style' and el.text: urls = [ # (start_pos, url) _unquote_match(match.group(1), match.start(1))[::-1] for match in _iter_css_urls(el.text) ] + [ (match.start(1), match.group(1)) for match in _iter_css_imports(el.text) ] if urls: # sort by start pos to bring both match sets back into order # and reverse the list to report correct positions despite # modifications urls.sort(reverse=True) for start, url in urls: yield (el, None, url, start) if 'style' in attribs: urls = list(_iter_css_urls(attribs['style'])) if urls: # return in reversed order to simplify in-place modifications for match in urls[::-1]: url, start = _unquote_match(match.group(1), match.start(1)) yield (el, 'style', url, start)
Rewrite all the links in the document. For each link link_repl_func ( link ) will be called and the return value will replace the old link.
def rewrite_links(self, link_repl_func, resolve_base_href=True, base_href=None): """ Rewrite all the links in the document. For each link ``link_repl_func(link)`` will be called, and the return value will replace the old link. Note that links may not be absolute (unless you first called ``make_links_absolute()``), and may be internal (e.g., ``'#anchor'``). They can also be values like ``'mailto:email'`` or ``'javascript:expr'``. If you give ``base_href`` then all links passed to ``link_repl_func()`` will take that into account. If the ``link_repl_func`` returns None, the attribute or tag text will be removed completely. """ if base_href is not None: # FIXME: this can be done in one pass with a wrapper # around link_repl_func self.make_links_absolute( base_href, resolve_base_href=resolve_base_href) elif resolve_base_href: self.resolve_base_href() for el, attrib, link, pos in self.iterlinks(): new_link = link_repl_func(link.strip()) if new_link == link: continue if new_link is None: # Remove the attribute or element content if attrib is None: el.text = '' else: del el.attrib[attrib] continue if attrib is None: new = el.text[:pos] + new_link + el.text[pos+len(link):] el.text = new else: cur = el.get(attrib) if not pos and len(cur) == len(link): new = new_link # most common case else: new = cur[:pos] + new_link + cur[pos+len(link):] el.set(attrib, new)
Return a list of tuples of the field values for the form. This is suitable to be passed to urllib. urlencode ().
def form_values(self): """ Return a list of tuples of the field values for the form. This is suitable to be passed to ``urllib.urlencode()``. """ results = [] for el in self.inputs: name = el.name if not name: continue tag = _nons(el.tag) if tag == 'textarea': results.append((name, el.value)) elif tag == 'select': value = el.value if el.multiple: for v in value: results.append((name, v)) elif value is not None: results.append((name, el.value)) else: assert tag == 'input', ( "Unexpected tag: %r" % el) if el.checkable and not el.checked: continue if el.type in ('submit', 'image', 'reset'): continue value = el.value if value is not None: results.append((name, el.value)) return results
Get/ set the form s action attribute.
def _action__get(self): """ Get/set the form's ``action`` attribute. """ base_url = self.base_url action = self.get('action') if base_url and action is not None: return urljoin(base_url, action) else: return action
Get/ set the value ( which is the contents of this element )
def _value__get(self): """ Get/set the value (which is the contents of this element) """ content = self.text or '' if self.tag.startswith("{%s}" % XHTML_NAMESPACE): serialisation_method = 'xml' else: serialisation_method = 'html' for el in self: # it's rare that we actually get here, so let's not use ''.join() content += etree.tostring( el, method=serialisation_method, encoding='unicode') return content
Get/ set the value of this select ( the selected option ).
def _value__get(self): """ Get/set the value of this select (the selected option). If this is a multi-select, this is a set-like object that represents all the selected options. """ if self.multiple: return MultipleSelectOptions(self) for el in _options_xpath(self): if el.get('selected') is not None: value = el.get('value') if value is None: value = el.text or '' if value: value = value.strip() return value return None
All the possible values this select can have ( the value attribute of all the <option > elements.
def value_options(self): """ All the possible values this select can have (the ``value`` attribute of all the ``<option>`` elements. """ options = [] for el in _options_xpath(self): value = el.get('value') if value is None: value = el.text or '' if value: value = value.strip() options.append(value) return options
Get/ set the value of this element using the value attribute.
def _value__get(self): """ Get/set the value of this element, using the ``value`` attribute. Also, if this is a checkbox and it has no value, this defaults to ``'on'``. If it is a checkbox or radio that is not checked, this returns None. """ if self.checkable: if self.checked: return self.get('value') or 'on' else: return None return self.get('value')
Get/ set the element this label points to. Return None if it can t be found.
def _for_element__get(self): """ Get/set the element this label points to. Return None if it can't be found. """ id = self.get('for') if not id: return None return self.body.get_element_by_id(id)
given a class/ instance return the full class path ( eg prefix. module. Classname )
def classpath(v): """given a class/instance return the full class path (eg, prefix.module.Classname) :param v: class or instance :returns: string, the full classpath of v """ if isinstance(v, type): ret = strclass(v) else: ret = strclass(v.__class__) return ret
iterate through the attributes of every logger s handler
def loghandler_members(): """iterate through the attributes of every logger's handler this is used to switch out stderr and stdout in tests when buffer is True :returns: generator of tuples, each tuple has (name, handler, member_name, member_val) """ Members = namedtuple("Members", ["name", "handler", "member_name", "member"]) log_manager = logging.Logger.manager loggers = [] ignore = set([modname()]) if log_manager.root: loggers = list(log_manager.loggerDict.items()) loggers.append(("root", log_manager.root)) for logger_name, logger in loggers: if logger_name in ignore: continue for handler in getattr(logger, "handlers", []): members = inspect.getmembers(handler) for member_name, member in members: yield Members(logger_name, handler, member_name, member)
return test counts that are set via pyt environment variables when pyt runs the test
def get_counts(): """return test counts that are set via pyt environment variables when pyt runs the test :returns: dict, 3 keys (classes, tests, modules) and how many tests of each were found by pyt """ counts = {} ks = [ ('PYT_TEST_CLASS_COUNT', "classes"), ('PYT_TEST_COUNT', "tests"), ('PYT_TEST_MODULE_COUNT', "modules"), ] for ek, cn in ks: counts[cn] = int(os.environ.get(ek, 0)) return counts
Returns True if only a single class is being run or some tests within a single class
def is_single_class(): """Returns True if only a single class is being run or some tests within a single class""" ret = False counts = get_counts() if counts["classes"] < 1 and counts["modules"] < 1: ret = counts["tests"] > 0 else: ret = counts["classes"] <= 1 and counts["modules"] <= 1 return ret
Returns True if only a module is being run
def is_single_module(): """Returns True if only a module is being run""" ret = False counts = get_counts() if counts["modules"] == 1: ret = True elif counts["modules"] < 1: ret = is_single_class() return ret
Validate request params.
def validate_params(request): """Validate request params.""" if 'params' in request: correct_params = isinstance(request['params'], (list, dict)) error = 'Incorrect parameter values' assert correct_params, error
Validate request id.
def validate_id(request): """Validate request id.""" if 'id' in request: correct_id = isinstance( request['id'], (string_types, int, None), ) error = 'Incorrect identifier' assert correct_id, error
Ensure that the given path is decoded NONE when no expected encoding works
def filesys_decode(path): """ Ensure that the given path is decoded, NONE when no expected encoding works """ fs_enc = sys.getfilesystemencoding() if isinstance(path, decoded_string): return path for enc in (fs_enc, "utf-8"): try: return path.decode(enc) except UnicodeDecodeError: continue
Helper for various string - wrapped functions.
def _escape_argspec(obj, iterable, escape): """Helper for various string-wrapped functions.""" for key, value in iterable: if hasattr(value, '__html__') or isinstance(value, string_types): obj[key] = escape(value) return obj
Return the python codec name corresponding to an encoding or None if the string doesn t correspond to a valid encoding.
def codecName(encoding): """Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.""" if isinstance(encoding, bytes): try: encoding = encoding.decode("ascii") except UnicodeDecodeError: return None if encoding: canonicalName = ascii_punctuation_re.sub("", encoding).lower() return encodings.get(canonicalName, None) else: return None
Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None
def detectBOM(self): """Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None""" bomDict = { codecs.BOM_UTF8: 'utf-8', codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_UTF16_BE: 'utf-16-be', codecs.BOM_UTF32_LE: 'utf-32-le', codecs.BOM_UTF32_BE: 'utf-32-be' } # Go to beginning of file and read in 4 bytes string = self.rawStream.read(4) assert isinstance(string, bytes) # Try detecting the BOM using bytes from the string encoding = bomDict.get(string[:3]) # UTF-8 seek = 3 if not encoding: # Need to detect UTF-32 before UTF-16 encoding = bomDict.get(string) # UTF-32 seek = 4 if not encoding: encoding = bomDict.get(string[:2]) # UTF-16 seek = 2 # Set the read position past the BOM if one was found, otherwise # set it to the start of the stream self.rawStream.seek(encoding and seek or 0) return encoding
Selects the new remote addr from the given list of ips in X - Forwarded - For. By default it picks the one that the num_proxies proxy server provides. Before 0. 9 it would always pick the first.
def get_remote_addr(self, forwarded_for): """Selects the new remote addr from the given list of ips in X-Forwarded-For. By default it picks the one that the `num_proxies` proxy server provides. Before 0.9 it would always pick the first. .. versionadded:: 0.8 """ if len(forwarded_for) >= self.num_proxies: return forwarded_for[-1 * self.num_proxies]
Substitutes symbols in CLDR number pattern.
def sub_symbols(pattern, code, symbol): """Substitutes symbols in CLDR number pattern.""" return pattern.replace('¤¤', code).replace('¤', symbol)
Converts amount value from several types into Decimal.
def amount_converter(obj): """Converts amount value from several types into Decimal.""" if isinstance(obj, Decimal): return obj elif isinstance(obj, (str, int, float)): return Decimal(str(obj)) else: raise ValueError('do not know how to convert: {}'.format(type(obj)))
Parse a string of HTML data into an Element tree using the BeautifulSoup parser.
def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs): """Parse a string of HTML data into an Element tree using the BeautifulSoup parser. Returns the root ``<html>`` Element of the tree. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent Element factory function through the `makeelement` keyword. By default, the standard ``BeautifulSoup`` class and the default factory of `lxml.html` are used. """ return _parse(data, beautifulsoup, makeelement, **bsargs)
Parse a file into an ElemenTree using the BeautifulSoup parser.
def parse(file, beautifulsoup=None, makeelement=None, **bsargs): """Parse a file into an ElemenTree using the BeautifulSoup parser. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent Element factory function through the `makeelement` keyword. By default, the standard ``BeautifulSoup`` class and the default factory of `lxml.html` are used. """ if not hasattr(file, 'read'): file = open(file) root = _parse(file, beautifulsoup, makeelement, **bsargs) return etree.ElementTree(root)
Convert a BeautifulSoup tree to a list of Element trees.
def convert_tree(beautiful_soup_tree, makeelement=None): """Convert a BeautifulSoup tree to a list of Element trees. Returns a list instead of a single root Element to support HTML-like soup with more than one root element. You can pass a different Element factory through the `makeelement` keyword. """ if makeelement is None: makeelement = html.html_parser.makeelement root = _convert_tree(beautiful_soup_tree, makeelement) children = root.getchildren() for child in children: root.remove(child) return children
Get the current exception info as Traceback object. Per default calling this method will reraise system exceptions such as generator exit system exit or others. This behavior can be disabled by passing False to the function as first parameter.
def get_current_traceback(ignore_system_exceptions=False, show_hidden_frames=False, skip=0): """Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavior can be disabled by passing `False` to the function as first parameter. """ exc_type, exc_value, tb = sys.exc_info() if ignore_system_exceptions and exc_type in system_exceptions: raise for x in range_type(skip): if tb.tb_next is None: break tb = tb.tb_next tb = Traceback(exc_type, exc_value, tb) if not show_hidden_frames: tb.filter_hidden_frames() return tb
String representation of the exception.
def exception(self): """String representation of the exception.""" buf = traceback.format_exception_only(self.exc_type, self.exc_value) rv = ''.join(buf).strip() return rv.decode('utf-8', 'replace') if PY2 else rv
Render the traceback for the interactive console.
def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is_syntax_error: title = u'Syntax Error' else: title = u'Traceback <em>(most recent call last)</em>:' for frame in self.frames: frames.append(u'<li%s>%s' % ( frame.info and u' title="%s"' % escape(frame.info) or u'', frame.render() )) if self.is_syntax_error: description_wrapper = u'<pre class=syntaxerror>%s</pre>' else: description_wrapper = u'<blockquote>%s</blockquote>' return SUMMARY_HTML % { 'classes': u' '.join(classes), 'title': title and u'<h3>%s</h3>' % title or u'', 'frames': u'\n'.join(frames), 'description': description_wrapper % escape(self.exception) }
Like the plaintext attribute but returns a generator
def generate_plaintext_traceback(self): """Like the plaintext attribute but returns a generator""" yield u'Traceback (most recent call last):' for frame in self.frames: yield u' File "%s", line %s, in %s' % ( frame.filename, frame.lineno, frame.function_name ) yield u' ' + frame.current_line.strip() yield self.exception
Helper function that returns lines with extra information.
def get_annotated_lines(self): """Helper function that returns lines with extra information.""" lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)] # find function definition and mark lines if hasattr(self.code, 'co_firstlineno'): lineno = self.code.co_firstlineno - 1 while lineno > 0: if _funcdef_re.match(lines[lineno].code): break lineno -= 1 try: offset = len(inspect.getblock([x.code + '\n' for x in lines[lineno:]])) except TokenError: offset = 0 for line in lines[lineno:lineno + offset]: line.in_frame = True # mark current line try: lines[self.lineno - 1].current = True except IndexError: pass return lines
Render the sourcecode.
def render_source(self): """Render the sourcecode.""" return SOURCE_TABLE_HTML % u'\n'.join(line.render() for line in self.get_annotated_lines())
Pull the version part out of a string.
def egg_info_matches( egg_info, search_name, link, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Pull the version part out of a string. :param egg_info: The string to parse. E.g. foo-2.1 :param search_name: The name of the package this belongs to. None to infer the name. Note that this cannot unambiguously parse strings like foo-2-2 which might be foo, 2-2 or foo-2, 2. :param link: The link the string came from, for logging on failure. """ match = _egg_info_re.search(egg_info) if not match: logger.debug('Could not parse version from link: %s', link) return None if search_name is None: full_match = match.group(0) return full_match[full_match.index('-'):] name = match.group(0).lower() # To match the "safe" name that pkg_resources creates: name = name.replace('_', '-') # project name and version must be separated by a dash look_for = search_name.lower() + "-" if name.startswith(look_for): return match.group(0)[len(look_for):] else: return None
Sort locations into files ( archives ) and urls and return a pair of lists ( files urls )
def _sort_locations(locations, expand_dir=False): """ Sort locations into "files" (archives) and "urls", and return a pair of lists (files,urls) """ files = [] urls = [] # puts the url for the given file path into the appropriate list def sort_path(path): url = path_to_url(path) if mimetypes.guess_type(url, strict=False)[0] == 'text/html': urls.append(url) else: files.append(url) for url in locations: is_local_path = os.path.exists(url) is_file_url = url.startswith('file:') if is_local_path or is_file_url: if is_local_path: path = url else: path = url_to_path(url) if os.path.isdir(path): if expand_dir: path = os.path.realpath(path) for item in os.listdir(path): sort_path(os.path.join(path, item)) elif is_file_url: urls.append(url) elif os.path.isfile(path): sort_path(path) else: urls.append(url) return files, urls
Function used to generate link sort key for link tuples. The greater the return value the more preferred it is. If not finding wheels then sorted by version only. If finding wheels then the sort order is by version then: 1. existing installs 2. wheels ordered via Wheel. support_index_min () 3. source archives Note: it was considered to embed this logic into the Link comparison operators but then different sdist links with the same version would have to be considered equal
def _candidate_sort_key(self, candidate): """ Function used to generate link sort key for link tuples. The greater the return value, the more preferred it is. If not finding wheels, then sorted by version only. If finding wheels, then the sort order is by version, then: 1. existing installs 2. wheels ordered via Wheel.support_index_min() 3. source archives Note: it was considered to embed this logic into the Link comparison operators, but then different sdist links with the same version, would have to be considered equal """ support_num = len(supported_tags) if candidate.location == INSTALLED_VERSION: pri = 1 elif candidate.location.is_wheel: # can raise InvalidWheelFilename wheel = Wheel(candidate.location.filename) if not wheel.supported(): raise UnsupportedWheel( "%s is not a supported wheel for this platform. It " "can't be sorted." % wheel.filename ) pri = -(wheel.support_index_min()) else: # sdist pri = -(support_num) return (candidate.version, pri)
Bring the latest version ( and wheels ) to the front but maintain the existing ordering as secondary. See the docstring for _link_sort_key for details. This function is isolated for easier unit testing.
def _sort_versions(self, applicable_versions): """ Bring the latest version (and wheels) to the front, but maintain the existing ordering as secondary. See the docstring for `_link_sort_key` for details. This function is isolated for easier unit testing. """ return sorted( applicable_versions, key=self._candidate_sort_key, reverse=True )
Returns the locations found via self. index_urls
def _get_index_urls_locations(self, project_name): """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): loc = posixpath.join(url, project_url_name) # For maximum compatibility with easy_install, ensure the path # ends in a trailing slash. Although this isn't in the spec # (and PyPI can handle it without the slash) some other index # implementations might break if they relied on easy_install's # behavior. if not loc.endswith('/'): loc = loc + '/' return loc project_url_name = urllib_parse.quote(project_name.lower()) if self.index_urls: # Check that we have the url_name correctly spelled: # Only check main index if index URL is given main_index_url = Link( mkurl_pypi_url(self.index_urls[0]), trusted=True, ) page = self._get_page(main_index_url) if page is None and PyPI.netloc not in str(main_index_url): warnings.warn( "Failed to find %r at %s. It is suggested to upgrade " "your index to support normalized names as the name in " "/simple/{name}." % (project_name, main_index_url), RemovedInPip8Warning, ) project_url_name = self._find_url_name( Link(self.index_urls[0], trusted=True), project_url_name, ) or project_url_name if project_url_name is not None: return [mkurl_pypi_url(url) for url in self.index_urls] return []
Find all available versions for project_name
def _find_all_versions(self, project_name): """Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned See _link_package_versions for details on which files are accepted """ index_locations = self._get_index_urls_locations(project_name) index_file_loc, index_url_loc = self._sort_locations(index_locations) fl_file_loc, fl_url_loc = self._sort_locations( self.find_links, expand_dir=True) dep_file_loc, dep_url_loc = self._sort_locations(self.dependency_links) file_locations = ( Link(url) for url in itertools.chain( index_file_loc, fl_file_loc, dep_file_loc) ) # We trust every url that the user has given us whether it was given # via --index-url or --find-links # We explicitly do not trust links that came from dependency_links # We want to filter out any thing which does not have a secure origin. url_locations = [ link for link in itertools.chain( (Link(url, trusted=True) for url in index_url_loc), (Link(url, trusted=True) for url in fl_url_loc), (Link(url) for url in dep_url_loc), ) if self._validate_secure_origin(logger, link) ] logger.debug('%d location(s) to search for versions of %s:', len(url_locations), project_name) for location in url_locations: logger.debug('* %s', location) canonical_name = pkg_resources.safe_name(project_name).lower() formats = fmt_ctl_formats(self.format_control, canonical_name) search = Search(project_name.lower(), canonical_name, formats) find_links_versions = self._package_versions( # We trust every directly linked archive in find_links (Link(url, '-f', trusted=True) for url in self.find_links), search ) page_versions = [] for page in self._get_pages(url_locations, project_name): logger.debug('Analyzing links from page %s', page.url) with indent_log(): page_versions.extend( self._package_versions(page.links, search) ) dependency_versions = self._package_versions( (Link(url) for url in self.dependency_links), search ) if dependency_versions: logger.debug( 'dependency_links found: %s', ', '.join([ version.location.url for version in dependency_versions ]) ) file_versions = self._package_versions(file_locations, search) if file_versions: file_versions.sort(reverse=True) logger.debug( 'Local files found: %s', ', '.join([ url_to_path(candidate.location.url) for candidate in file_versions ]) ) # This is an intentional priority ordering return ( file_versions + find_links_versions + page_versions + dependency_versions )
Try to find an InstallationCandidate for req
def find_requirement(self, req, upgrade): """Try to find an InstallationCandidate for req Expects req, an InstallRequirement and upgrade, a boolean Returns an InstallationCandidate or None May raise DistributionNotFound or BestVersionAlreadyInstalled """ all_versions = self._find_all_versions(req.name) # Filter out anything which doesn't match our specifier _versions = set( req.specifier.filter( [x.version for x in all_versions], prereleases=( self.allow_all_prereleases if self.allow_all_prereleases else None ), ) ) applicable_versions = [ x for x in all_versions if x.version in _versions ] if req.satisfied_by is not None: # Finally add our existing versions to the front of our versions. applicable_versions.insert( 0, InstallationCandidate( req.name, req.satisfied_by.version, INSTALLED_VERSION, ) ) existing_applicable = True else: existing_applicable = False applicable_versions = self._sort_versions(applicable_versions) if not upgrade and existing_applicable: if applicable_versions[0].location is INSTALLED_VERSION: logger.debug( 'Existing installed version (%s) is most up-to-date and ' 'satisfies requirement', req.satisfied_by.version, ) else: logger.debug( 'Existing installed version (%s) satisfies requirement ' '(most up-to-date version is %s)', req.satisfied_by.version, applicable_versions[0][2], ) return None if not applicable_versions: logger.critical( 'Could not find a version that satisfies the requirement %s ' '(from versions: %s)', req, ', '.join( sorted( set(str(i.version) for i in all_versions), key=parse_version, ) ) ) if self.need_warn_external: logger.warning( "Some externally hosted files were ignored as access to " "them may be unreliable (use --allow-external %s to " "allow).", req.name, ) if self.need_warn_unverified: logger.warning( "Some insecure and unverifiable files were ignored" " (use --allow-unverified %s to allow).", req.name, ) raise DistributionNotFound( 'No matching distribution found for %s' % req ) if applicable_versions[0].location is INSTALLED_VERSION: # We have an existing version, and its the best version logger.debug( 'Installed version (%s) is most up-to-date (past versions: ' '%s)', req.satisfied_by.version, ', '.join(str(i.version) for i in applicable_versions[1:]) or "none", ) raise BestVersionAlreadyInstalled if len(applicable_versions) > 1: logger.debug( 'Using version %s (newest of versions: %s)', applicable_versions[0].version, ', '.join(str(i.version) for i in applicable_versions) ) selected_version = applicable_versions[0].location if (selected_version.verifiable is not None and not selected_version.verifiable): logger.warning( "%s is potentially insecure and unverifiable.", req.name, ) return selected_version
Yields ( page page_url ) from the given locations skipping locations that have errors and adding download/ homepage links
def _get_pages(self, locations, project_name): """ Yields (page, page_url) from the given locations, skipping locations that have errors, and adding download/homepage links """ all_locations = list(locations) seen = set() normalized = normalize_name(project_name) while all_locations: location = all_locations.pop(0) if location in seen: continue seen.add(location) page = self._get_page(location) if page is None: continue yield page for link in page.rel_links(): if (normalized not in self.allow_external and not self.allow_all_external): self.need_warn_external = True logger.debug( "Not searching %s for files because external " "urls are disallowed.", link, ) continue if (link.trusted is not None and not link.trusted and normalized not in self.allow_unverified): logger.debug( "Not searching %s for urls, it is an " "untrusted link and cannot produce safe or " "verifiable files.", link, ) self.need_warn_unverified = True continue all_locations.append(link)
Returns elements of links in order non - egg links first egg links second while eliminating duplicates
def _sort_links(self, links): """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() for link in links: if link not in seen: seen.add(link) if link.egg_fragment: eggs.append(link) else: no_eggs.append(link) return no_eggs + eggs
Return an InstallationCandidate or None
def _link_package_versions(self, link, search): """Return an InstallationCandidate or None""" platform = get_platform() version = None if link.egg_fragment: egg_info = link.egg_fragment ext = link.ext else: egg_info, ext = link.splitext() if not ext: self._log_skipped_link(link, 'not a file') return if ext not in SUPPORTED_EXTENSIONS: self._log_skipped_link( link, 'unsupported archive format: %s' % ext) return if "binary" not in search.formats and ext == wheel_ext: self._log_skipped_link( link, 'No binaries permitted for %s' % search.supplied) return if "macosx10" in link.path and ext == '.zip': self._log_skipped_link(link, 'macosx10 one') return if ext == wheel_ext: try: wheel = Wheel(link.filename) except InvalidWheelFilename: self._log_skipped_link(link, 'invalid wheel filename') return if (pkg_resources.safe_name(wheel.name).lower() != search.canonical): self._log_skipped_link( link, 'wrong project name (not %s)' % search.supplied) return if not wheel.supported(): self._log_skipped_link( link, 'it is not compatible with this Python') return # This is a dirty hack to prevent installing Binary Wheels from # PyPI unless it is a Windows or Mac Binary Wheel. This is # paired with a change to PyPI disabling uploads for the # same. Once we have a mechanism for enabling support for # binary wheels on linux that deals with the inherent problems # of binary distribution this can be removed. comes_from = getattr(link, "comes_from", None) if ( ( not platform.startswith('win') and not platform.startswith('macosx') and not platform == 'cli' ) and comes_from is not None and urllib_parse.urlparse( comes_from.url ).netloc.endswith(PyPI.netloc)): if not wheel.supported(tags=supported_tags_noarch): self._log_skipped_link( link, "it is a pypi-hosted binary " "Wheel on an unsupported platform", ) return version = wheel.version # This should be up by the search.ok_binary check, but see issue 2700. if "source" not in search.formats and ext != wheel_ext: self._log_skipped_link( link, 'No sources permitted for %s' % search.supplied) return if not version: version = egg_info_matches(egg_info, search.supplied, link) if version is None: self._log_skipped_link( link, 'wrong project name (not %s)' % search.supplied) return if (link.internal is not None and not link.internal and not normalize_name(search.supplied).lower() in self.allow_external and not self.allow_all_external): # We have a link that we are sure is external, so we should skip # it unless we are allowing externals self._log_skipped_link(link, 'it is externally hosted') self.need_warn_external = True return if (link.verifiable is not None and not link.verifiable and not (normalize_name(search.supplied).lower() in self.allow_unverified)): # We have a link that we are sure we cannot verify its integrity, # so we should skip it unless we are allowing unsafe installs # for this requirement. self._log_skipped_link( link, 'it is an insecure and unverifiable file') self.need_warn_unverified = True return match = self._py_version_re.search(version) if match: version = version[:match.start()] py_version = match.group(1) if py_version != sys.version[:3]: self._log_skipped_link( link, 'Python version is incorrect') return logger.debug('Found link %s, version: %s', link, version) return InstallationCandidate(search.supplied, version, link)
Get the Content - Type of the given url using a HEAD request
def _get_content_type(url, session): """Get the Content-Type of the given url, using a HEAD request""" scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in ('http', 'https'): # FIXME: some warning or something? # assertion error? return '' resp = session.head(url, allow_redirects=True) resp.raise_for_status() return resp.headers.get("Content-Type", "")
Yields all links in the page
def links(self): """Yields all links in the page""" for anchor in self.parsed.findall(".//a"): if anchor.get("href"): href = anchor.get("href") url = self.clean_link( urllib_parse.urljoin(self.base_url, href) ) # Determine if this link is internal. If that distinction # doesn't make sense in this context, then we don't make # any distinction. internal = None if self.api_version and self.api_version >= 2: # Only api_versions >= 2 have a distinction between # external and internal links internal = bool( anchor.get("rel") and "internal" in anchor.get("rel").split() ) yield Link(url, self, internal=internal)
Returns True if this link can be verified after download False if it cannot and None if we cannot determine.
def verifiable(self): """ Returns True if this link can be verified after download, False if it cannot, and None if we cannot determine. """ trusted = self.trusted or getattr(self.comes_from, "trusted", None) if trusted is not None and trusted: # This link came from a trusted source. It *may* be verifiable but # first we need to see if this page is operating under the new # API version. try: api_version = getattr(self.comes_from, "api_version", None) api_version = int(api_version) except (ValueError, TypeError): api_version = None if api_version is None or api_version <= 1: # This link is either trusted, or it came from a trusted, # however it is not operating under the API version 2 so # we can't make any claims about if it's safe or not return if self.hash: # This link came from a trusted source and it has a hash, so we # can consider it safe. return True else: # This link came from a trusted source, using the new API # version, and it does not have a hash. It is NOT verifiable return False elif trusted is not None: # This link came from an untrusted source and we cannot trust it return False
Determines if this points to an actual artifact ( e. g. a tarball ) or if it points to an abstract thing like a path or a VCS location.
def is_artifact(self): """ Determines if this points to an actual artifact (e.g. a tarball) or if it points to an "abstract" thing like a path or a VCS location. """ from pip.vcs import vcs if self.scheme in vcs.all_schemes: return False return True
Generate list of ( package src_dir build_dir filenames ) tuples
def _get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" self.analyze_manifest() data = [] for package in self.packages or (): # Locate package source directory src_dir = self.get_package_dir(package) # Compute package build directory build_dir = os.path.join(*([self.build_lib] + package.split('.'))) # Length of path to strip from found files plen = len(src_dir) + 1 # Strip directory from globbed filenames filenames = [ file[plen:] for file in self.find_data_files(package, src_dir) ] data.append((package, src_dir, build_dir, filenames)) return data
Return filenames for package s data files in src_dir
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = self.manifest_files.get(package, [])[:] for pattern in globs: # Each pattern has to be converted to a platform-specific path files.extend(glob(os.path.join(src_dir, convert_path(pattern)))) return self.exclude_data_files(package, src_dir, files)
Check namespace packages __init__ for declare_namespace
def check_package(self, package, package_dir): """Check namespace packages' __init__ for declare_namespace""" try: return self.packages_checked[package] except KeyError: pass init_py = orig.build_py.check_package(self, package, package_dir) self.packages_checked[package] = init_py if not init_py or not self.distribution.namespace_packages: return init_py for pkg in self.distribution.namespace_packages: if pkg == package or pkg.startswith(package + '.'): break else: return init_py f = open(init_py, 'rbU') if 'declare_namespace'.encode() not in f.read(): from distutils.errors import DistutilsError raise DistutilsError( "Namespace package problem: %s is a namespace package, but " "its\n__init__.py does not call declare_namespace()! Please " 'fix it.\n(See the setuptools manual under ' '"Namespace Packages" for details.)\n"' % (package,) ) f.close() return init_py
Filter filenames for package s data files in src_dir
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, [])) bad = [] for pattern in globs: bad.extend( fnmatch.filter( files, os.path.join(src_dir, convert_path(pattern)) ) ) bad = dict.fromkeys(bad) seen = {} return [ f for f in files if f not in bad and f not in seen and seen.setdefault(f, 1) # ditch dupes ]
Parse a requirements file and yield InstallRequirement instances.
def parse_requirements(filename, finder=None, comes_from=None, options=None, session=None, wheel_cache=None): """ Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: Global options. :param session: Instance of pip.download.PipSession. :param wheel_cache: Instance of pip.wheel.WheelCache """ if session is None: raise TypeError( "parse_requirements() missing 1 required keyword argument: " "'session'" ) _, content = get_file_content( filename, comes_from=comes_from, session=session ) lines = content.splitlines() lines = ignore_comments(lines) lines = join_lines(lines) lines = skip_regex(lines, options) for line_number, line in enumerate(lines, 1): req_iter = process_line(line, filename, line_number, finder, comes_from, options, session, wheel_cache) for req in req_iter: yield req
Process a single requirements line ; This can result in creating/ yielding requirements or updating the finder.
def process_line(line, filename, line_number, finder=None, comes_from=None, options=None, session=None, wheel_cache=None): """Process a single requirements line; This can result in creating/yielding requirements, or updating the finder. For lines that contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS_REQ, and they are scoped to the requirement. Other options from SUPPORTED_OPTIONS may be present, but are ignored. For lines that do not contain requirements, the only options that have an effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may be present, but are ignored. These lines may contain multiple options (although our docs imply only one is supported), and all our parsed and affect the finder. """ parser = build_parser() defaults = parser.get_default_values() defaults.index_url = None if finder: # `finder.format_control` will be updated during parsing defaults.format_control = finder.format_control args_str, options_str = break_args_options(line) opts, _ = parser.parse_args(shlex.split(options_str), defaults) # yield a line requirement if args_str: comes_from = '-r %s (line %s)' % (filename, line_number) isolated = options.isolated_mode if options else False if options: cmdoptions.check_install_build_global(options, opts) # get the options that apply to requirements req_options = {} for dest in SUPPORTED_OPTIONS_REQ_DEST: if dest in opts.__dict__ and opts.__dict__[dest]: req_options[dest] = opts.__dict__[dest] yield InstallRequirement.from_line( args_str, comes_from, isolated=isolated, options=req_options, wheel_cache=wheel_cache ) # yield an editable requirement elif opts.editables: comes_from = '-r %s (line %s)' % (filename, line_number) isolated = options.isolated_mode if options else False default_vcs = options.default_vcs if options else None yield InstallRequirement.from_editable( opts.editables[0], comes_from=comes_from, default_vcs=default_vcs, isolated=isolated, wheel_cache=wheel_cache ) # parse a nested requirements file elif opts.requirements: req_path = opts.requirements[0] # original file is over http if SCHEME_RE.search(filename): # do a url join so relative paths work req_path = urllib_parse.urljoin(filename, req_path) # original file and nested file are paths elif not SCHEME_RE.search(req_path): # do a join so relative paths work req_dir = os.path.dirname(filename) req_path = os.path.join(os.path.dirname(filename), req_path) # TODO: Why not use `comes_from='-r {} (line {})'` here as well? parser = parse_requirements( req_path, finder, comes_from, options, session, wheel_cache=wheel_cache ) for req in parser: yield req # set finder options elif finder: if opts.index_url: finder.index_urls = [opts.index_url] if opts.use_wheel is False: finder.use_wheel = False pip.index.fmt_ctl_no_use_wheel(finder.format_control) if opts.no_index is True: finder.index_urls = [] if opts.allow_all_external: finder.allow_all_external = opts.allow_all_external if opts.extra_index_urls: finder.index_urls.extend(opts.extra_index_urls) if opts.allow_external: finder.allow_external |= set( [normalize_name(v).lower() for v in opts.allow_external]) if opts.allow_unverified: # Remove after 7.0 finder.allow_unverified |= set( [normalize_name(v).lower() for v in opts.allow_unverified]) if opts.find_links: # FIXME: it would be nice to keep track of the source # of the find_links: support a find-links local path # relative to a requirements file. value = opts.find_links[0] req_dir = os.path.dirname(os.path.abspath(filename)) relative_to_reqs_file = os.path.join(req_dir, value) if os.path.exists(relative_to_reqs_file): value = relative_to_reqs_file finder.find_links.append(value)
Joins a line ending in \ with the previous line.
def join_lines(iterator): """ Joins a line ending in '\' with the previous line. """ lines = [] for line in iterator: if not line.endswith('\\'): if lines: lines.append(line) yield ''.join(lines) lines = [] else: yield line else: lines.append(line.strip('\\'))
Strips and filters empty or commented lines.
def ignore_comments(iterator): """ Strips and filters empty or commented lines. """ for line in iterator: line = COMMENT_RE.sub('', line) line = line.strip() if line: yield line
Optionally exclude lines that match -- skip - requirements - regex
def skip_regex(lines, options): """ Optionally exclude lines that match '--skip-requirements-regex' """ skip_regex = options.skip_requirements_regex if options else None if skip_regex: lines = filterfalse(re.compile(skip_regex).search, lines) return lines
Return compiled marker as a function accepting an environment dict.
def compile(marker): """Return compiled marker as a function accepting an environment dict.""" try: return _cache[marker] except KeyError: pass if not marker.strip(): def marker_fn(environment=None, override=None): """""" return True else: compiled_marker = compile_marker(parse_marker(marker)) def marker_fn(environment=None, override=None): """override updates environment""" if override is None: override = {} if environment is None: environment = default_environment() environment.update(override) return eval(compiled_marker, environment) marker_fn.__doc__ = marker _cache[marker] = marker_fn return _cache[marker]
Ensure statement only contains allowed nodes.
def visit(self, node): """Ensure statement only contains allowed nodes.""" if not isinstance(node, self.ALLOWED): raise SyntaxError('Not allowed in environment markers.\n%s\n%s' % (self.statement, (' ' * node.col_offset) + '^')) return ast.NodeTransformer.visit(self, node)
Flatten one level of attribute access.
def visit_Attribute(self, node): """Flatten one level of attribute access.""" new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx) return ast.copy_location(new_node, node)
coerce takes a value and attempts to convert it to a float or int.
def coerce(value): """ coerce takes a value and attempts to convert it to a float, or int. If none of the conversions are successful, the original value is returned. >>> coerce('3') 3 >>> coerce('3.0') 3.0 >>> coerce('foo') 'foo' >>> coerce({}) {} >>> coerce('{}') '{}' """ with contextlib2.suppress(Exception): loaded = json.loads(value) assert isinstance(loaded, numbers.Number) return loaded return value
A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called.
def copy_current_request_context(f): """A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request like you # would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10 """ top = _request_ctx_stack.top if top is None: raise RuntimeError('This decorator can only be used at local scopes ' 'when a request context is on the stack. For instance within ' 'view functions.') reqctx = top.copy() def wrapper(*args, **kwargs): with reqctx: return f(*args, **kwargs) return update_wrapper(wrapper, f)
Binds the app context to the current context.
def push(self): """Binds the app context to the current context.""" self._refcnt += 1 _app_ctx_stack.push(self) appcontext_pushed.send(self.app)
Pops the app context.
def pop(self, exc=None): """Pops the app context.""" self._refcnt -= 1 if self._refcnt <= 0: if exc is None: exc = sys.exc_info()[1] self.app.do_teardown_appcontext(exc) rv = _app_ctx_stack.pop() assert rv is self, 'Popped wrong app context. (%r instead of %r)' \ % (rv, self) appcontext_popped.send(self.app)
Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked.
def copy(self): """Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked. .. versionadded:: 0.10 """ return self.__class__(self.app, environ=self.request.environ, request=self.request )
Can be overridden by a subclass to hook into the matching of the request.
def match_request(self): """Can be overridden by a subclass to hook into the matching of the request. """ try: url_rule, self.request.view_args = \ self.url_adapter.match(return_rule=True) self.request.url_rule = url_rule except HTTPException as e: self.request.routing_exception = e
Binds the request context to the current context.
def push(self): """Binds the request context to the current context.""" # If an exception occurs in debug mode or if context preservation is # activated under exception situations exactly one context stays # on the stack. The rationale is that you want to access that # information under debug situations. However if someone forgets to # pop that context again we want to make sure that on the next push # it's invalidated, otherwise we run at risk that something leaks # memory. This is usually only a problem in testsuite since this # functionality is not active in production environments. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop(top._preserved_exc) # Before we push the request context we have to ensure that there # is an application context. app_ctx = _app_ctx_stack.top if app_ctx is None or app_ctx.app != self.app: app_ctx = self.app.app_context() app_ctx.push() self._implicit_app_ctx_stack.append(app_ctx) else: self._implicit_app_ctx_stack.append(None) _request_ctx_stack.push(self) # Open the session at the moment that the request context is # available. This allows a custom open_session method to use the # request context (e.g. code that access database information # stored on `g` instead of the appcontext). self.session = self.app.open_session(self.request) if self.session is None: self.session = self.app.make_null_session()
Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the: meth: ~flask. Flask. teardown_request decorator.
def pop(self, exc=None): """Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the :meth:`~flask.Flask.teardown_request` decorator. .. versionchanged:: 0.9 Added the `exc` argument. """ app_ctx = self._implicit_app_ctx_stack.pop() clear_request = False if not self._implicit_app_ctx_stack: self.preserved = False self._preserved_exc = None if exc is None: exc = sys.exc_info()[1] self.app.do_teardown_request(exc) # If this interpreter supports clearing the exception information # we do that now. This will only go into effect on Python 2.x, # on 3.x it disappears automatically at the end of the exception # stack. if hasattr(sys, 'exc_clear'): sys.exc_clear() request_close = getattr(self.request, 'close', None) if request_close is not None: request_close() clear_request = True rv = _request_ctx_stack.pop() assert rv is self, 'Popped wrong request context. (%r instead of %r)' \ % (rv, self) # get rid of circular dependencies at the end of the request # so that we don't require the GC to be active. if clear_request: rv.request.environ['werkzeug.request'] = None # Get rid of the app as well if necessary. if app_ctx is not None: app_ctx.pop(exc)
Figure out the name of a directory to back up the given dir to ( adding. bak. bak2 etc )
def backup_dir(dir, ext='.bak'): """Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)""" n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension
Returns true if all the paths have the same leading path name ( i. e. everything is in one subdirectory in an archive )
def has_leading_dir(paths): """Returns true if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive)""" common_prefix = None for path in paths: prefix, rest = split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True
Make a filename relative where the filename path and it is relative to rel_to
def make_path_relative(path, rel_to): """ Make a filename relative, where the filename path, and it is relative to rel_to >>> make_path_relative('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../../../something/a-file.pth' >>> make_path_relative('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../usr/share/something/a-file.pth' >>> make_path_relative('/usr/share/a-file.pth', '/usr/share/') 'a-file.pth' """ path_filename = os.path.basename(path) path = os.path.dirname(path) path = os.path.normpath(os.path.abspath(path)) rel_to = os.path.normpath(os.path.abspath(rel_to)) path_parts = path.strip(os.path.sep).split(os.path.sep) rel_to_parts = rel_to.strip(os.path.sep).split(os.path.sep) while path_parts and rel_to_parts and path_parts[0] == rel_to_parts[0]: path_parts.pop(0) rel_to_parts.pop(0) full_parts = ['..'] * len(rel_to_parts) + path_parts + [path_filename] if full_parts == ['']: return '.' + os.path.sep return os.path.sep.join(full_parts)
Return True if given Distribution is installed in user site.
def dist_in_usersite(dist): """ Return True if given Distribution is installed in user site. """ norm_path = normalize_path(dist_location(dist)) return norm_path.startswith(normalize_path(user_site))
Is distribution an editable install?
def dist_is_editable(dist): """Is distribution an editable install?""" # TODO: factor out determining editableness out of FrozenRequirement from pip import FrozenRequirement req = FrozenRequirement.from_dist(dist, []) return req.editable
Untar the file ( with path filename ) to the destination location. All files are written based on system defaults and umask ( i. e. permissions are not preserved ) except that regular file members with any execute permissions ( user group or world ) have chmod + x applied after being written. Note that for windows any execute changes using os. chmod are no - ops per the python docs.
def untar_file(filename, location): """ Untar the file (with path `filename`) to the destination `location`. All files are written based on system defaults and umask (i.e. permissions are not preserved), except that regular file members with any execute permissions (user, group, or world) have "chmod +x" applied after being written. Note that for windows, any execute changes using os.chmod are no-ops per the python docs. """ ensure_dir(location) if filename.lower().endswith('.gz') or filename.lower().endswith('.tgz'): mode = 'r:gz' elif filename.lower().endswith(BZ2_EXTENSIONS): mode = 'r:bz2' elif filename.lower().endswith('.tar'): mode = 'r' else: logger.warning( 'Cannot determine compression type for file %s', filename, ) mode = 'r:*' tar = tarfile.open(filename, mode) try: # note: python<=2.5 doesn't seem to know about pax headers, filter them leading = has_leading_dir([ member.name for member in tar.getmembers() if member.name != 'pax_global_header' ]) for member in tar.getmembers(): fn = member.name if fn == 'pax_global_header': continue if leading: fn = split_leading_dir(fn)[1] path = os.path.join(location, fn) if member.isdir(): ensure_dir(path) elif member.issym(): try: tar._extract_member(member, path) except Exception as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) logger.warning( 'In the tar file %s the member %s is invalid: %s', filename, member.name, exc, ) continue else: try: fp = tar.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) logger.warning( 'In the tar file %s the member %s is invalid: %s', filename, member.name, exc, ) continue ensure_dir(os.path.dirname(path)) destfp = open(path, 'wb') try: shutil.copyfileobj(fp, destfp) finally: destfp.close() fp.close() # member have any execute permissions for user/group/world? if member.mode & 0o111: # make dest file have execute for user/group/world # no-op on windows per python docs os.chmod(path, (0o777 - current_umask() | 0o111)) finally: tar.close()
Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the: meth: make_setup_state method.
def record(self, func): """Registers a function that is called when the blueprint is registered on the application. This function is called with the state as argument as returned by the :meth:`make_setup_state` method. """ if self._got_registered_once and self.warn_on_modifications: from warnings import warn warn(Warning('The blueprint was already registered once ' 'but is getting modified now. These changes ' 'will not show up.')) self.deferred_functions.append(func)
Creates an instance of: meth: ~flask. blueprints. BlueprintSetupState object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state.
def make_setup_state(self, app, options, first_registration=False): """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState` object that is later passed to the register callback functions. Subclasses can override this to return a subclass of the setup state. """ return BlueprintSetupState(self, app, options, first_registration)
Like: meth: Flask. endpoint but for a blueprint. This does not prefix the endpoint with the blueprint name this has to be done explicitly by the user of this method. If the endpoint is prefixed with a. it will be registered to the current blueprint otherwise it s an application independent endpoint.
def endpoint(self, endpoint): """Like :meth:`Flask.endpoint` but for a blueprint. This does not prefix the endpoint with the blueprint name, this has to be done explicitly by the user of this method. If the endpoint is prefixed with a `.` it will be registered to the current blueprint, otherwise it's an application independent endpoint. """ def decorator(f): def register_endpoint(state): state.app.view_functions[endpoint] = f self.record_once(register_endpoint) return f return decorator
Register a custom template filter available application wide. Like: meth: Flask. template_filter but for a blueprint.
def app_template_filter(self, name=None): """Register a custom template filter, available application wide. Like :meth:`Flask.template_filter` but for a blueprint. :param name: the optional name of the filter, otherwise the function name will be used. """ def decorator(f): self.add_app_template_filter(f, name=name) return f return decorator
Register a custom template filter available application wide. Like: meth: Flask. add_template_filter but for a blueprint. Works exactly like the: meth: app_template_filter decorator.
def add_app_template_filter(self, f, name=None): """Register a custom template filter, available application wide. Like :meth:`Flask.add_template_filter` but for a blueprint. Works exactly like the :meth:`app_template_filter` decorator. :param name: the optional name of the filter, otherwise the function name will be used. """ def register_template(state): state.app.jinja_env.filters[name or f.__name__] = f self.record_once(register_template)
Register a custom template global available application wide. Like: meth: Flask. template_global but for a blueprint.
def app_template_global(self, name=None): """Register a custom template global, available application wide. Like :meth:`Flask.template_global` but for a blueprint. .. versionadded:: 0.10 :param name: the optional name of the global, otherwise the function name will be used. """ def decorator(f): self.add_app_template_global(f, name=name) return f return decorator
Register a custom template global available application wide. Like: meth: Flask. add_template_global but for a blueprint. Works exactly like the: meth: app_template_global decorator.
def add_app_template_global(self, f, name=None): """Register a custom template global, available application wide. Like :meth:`Flask.add_template_global` but for a blueprint. Works exactly like the :meth:`app_template_global` decorator. .. versionadded:: 0.10 :param name: the optional name of the global, otherwise the function name will be used. """ def register_template(state): state.app.jinja_env.globals[name or f.__name__] = f self.record_once(register_template)
Like: meth: Flask. before_request but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint.
def before_request(self, f): """Like :meth:`Flask.before_request` but for a blueprint. This function is only executed before each request that is handled by a function of that blueprint. """ self.record_once(lambda s: s.app.before_request_funcs .setdefault(self.name, []).append(f)) return f
Like: meth: Flask. before_request. Such a function is executed before each request even if outside of a blueprint.
def before_app_request(self, f): """Like :meth:`Flask.before_request`. Such a function is executed before each request, even if outside of a blueprint. """ self.record_once(lambda s: s.app.before_request_funcs .setdefault(None, []).append(f)) return f
Like: meth: Flask. before_first_request. Such a function is executed before the first request to the application.
def before_app_first_request(self, f): """Like :meth:`Flask.before_first_request`. Such a function is executed before the first request to the application. """ self.record_once(lambda s: s.app.before_first_request_funcs.append(f)) return f
Like: meth: Flask. after_request but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint.
def after_request(self, f): """Like :meth:`Flask.after_request` but for a blueprint. This function is only executed after each request that is handled by a function of that blueprint. """ self.record_once(lambda s: s.app.after_request_funcs .setdefault(self.name, []).append(f)) return f
Like: meth: Flask. after_request but for a blueprint. Such a function is executed after each request even if outside of the blueprint.
def after_app_request(self, f): """Like :meth:`Flask.after_request` but for a blueprint. Such a function is executed after each request, even if outside of the blueprint. """ self.record_once(lambda s: s.app.after_request_funcs .setdefault(None, []).append(f)) return f
Like: meth: Flask. teardown_request but for a blueprint. This function is only executed when tearing down requests handled by a function of that blueprint. Teardown request functions are executed when the request context is popped even when no actual request was performed.
def teardown_request(self, f): """Like :meth:`Flask.teardown_request` but for a blueprint. This function is only executed when tearing down requests handled by a function of that blueprint. Teardown request functions are executed when the request context is popped, even when no actual request was performed. """ self.record_once(lambda s: s.app.teardown_request_funcs .setdefault(self.name, []).append(f)) return f
Like: meth: Flask. teardown_request but for a blueprint. Such a function is executed when tearing down each request even if outside of the blueprint.
def teardown_app_request(self, f): """Like :meth:`Flask.teardown_request` but for a blueprint. Such a function is executed when tearing down each request, even if outside of the blueprint. """ self.record_once(lambda s: s.app.teardown_request_funcs .setdefault(None, []).append(f)) return f
Like: meth: Flask. context_processor but for a blueprint. This function is only executed for requests handled by a blueprint.
def context_processor(self, f): """Like :meth:`Flask.context_processor` but for a blueprint. This function is only executed for requests handled by a blueprint. """ self.record_once(lambda s: s.app.template_context_processors .setdefault(self.name, []).append(f)) return f
Like: meth: Flask. context_processor but for a blueprint. Such a function is executed each request even if outside of the blueprint.
def app_context_processor(self, f): """Like :meth:`Flask.context_processor` but for a blueprint. Such a function is executed each request, even if outside of the blueprint. """ self.record_once(lambda s: s.app.template_context_processors .setdefault(None, []).append(f)) return f
Like: meth: Flask. errorhandler but for a blueprint. This handler is used for all requests even if outside of the blueprint.
def app_errorhandler(self, code): """Like :meth:`Flask.errorhandler` but for a blueprint. This handler is used for all requests, even if outside of the blueprint. """ def decorator(f): self.record_once(lambda s: s.app.errorhandler(code)(f)) return f return decorator
Registers a function as URL value preprocessor for this blueprint. It s called before the view functions are called and can modify the url values provided.
def url_value_preprocessor(self, f): """Registers a function as URL value preprocessor for this blueprint. It's called before the view functions are called and can modify the url values provided. """ self.record_once(lambda s: s.app.url_value_preprocessors .setdefault(self.name, []).append(f)) return f
Callback function for URL defaults for this blueprint. It s called with the endpoint and values and should update the values passed in place.
def url_defaults(self, f): """Callback function for URL defaults for this blueprint. It's called with the endpoint and values and should update the values passed in place. """ self.record_once(lambda s: s.app.url_default_functions .setdefault(self.name, []).append(f)) return f
Same as: meth: url_value_preprocessor but application wide.
def app_url_value_preprocessor(self, f): """Same as :meth:`url_value_preprocessor` but application wide. """ self.record_once(lambda s: s.app.url_value_preprocessors .setdefault(None, []).append(f)) return f
Same as: meth: url_defaults but application wide.
def app_url_defaults(self, f): """Same as :meth:`url_defaults` but application wide. """ self.record_once(lambda s: s.app.url_default_functions .setdefault(None, []).append(f)) return f
Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the application.
def errorhandler(self, code_or_exception): """Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the application. Otherwise works as the :meth:`~flask.Flask.errorhandler` decorator of the :class:`~flask.Flask` object. """ def decorator(f): self.record_once(lambda s: s.app._register_error_handler( self.name, code_or_exception, f)) return f return decorator