INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
This method is called to create the default OPTIONS response. This can be changed through subclassing to change the default behavior of OPTIONS responses.
def make_default_options_response(self): """This method is called to create the default `OPTIONS` response. This can be changed through subclassing to change the default behavior of `OPTIONS` responses. .. versionadded:: 0.7 """ adapter = _request_ctx_stack.top.url_adapt...
Converts the return value from a view function to a real response object that is an instance of: attr: response_class.
def make_response(self, rv): """Converts the return value from a view function to a real response object that is an instance of :attr:`response_class`. The following types are allowed for `rv`: .. tabularcolumns:: |p{3.5cm}|p{9.5cm}| ======================= ===================...
Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly.
def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now a...
Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building.
def inject_url_defaults(self, endpoint, values): """Injects the URL defaults for the given endpoint directly into the values dictionary passed. This is used internally and automatically called on URL building. .. versionadded:: 0.7 """ funcs = self.url_default_functions...
Handle: class: ~werkzeug. routing. BuildError on: meth: url_for.
def handle_url_build_error(self, error, endpoint, values): """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`. """ exc_type, exc_value, tb = sys.exc_info() for handler in self.url_build_error_handlers: try: rv = handler(error, endpoint, values)...
Called before the actual request dispatching and will call every as: meth: before_request decorated function. If any of these function returns a value it s handled as if it was the return value from the view and further request handling is stopped.
def preprocess_request(self): """Called before the actual request dispatching and will call every as :meth:`before_request` decorated function. If any of these function returns a value it's handled as if it was the return value from the view and further request handling is stoppe...
Can be overridden in order to modify the response object before it s sent to the WSGI server. By default this will call all the: meth: after_request decorated functions.
def process_response(self, response): """Can be overridden in order to modify the response object before it's sent to the WSGI server. By default this will call all the :meth:`after_request` decorated functions. .. versionchanged:: 0.5 As of Flask 0.5 the functions registere...
Called after the actual request dispatching and will call every as: meth: teardown_request decorated function. This is not actually called by the: class: Flask object itself but is always triggered when the request context is popped. That way we have a tighter control over certain resources under testing environments.
def do_teardown_request(self, exc=None): """Called after the actual request dispatching and will call every as :meth:`teardown_request` decorated function. This is not actually called by the :class:`Flask` object itself but is always triggered when the request context is popped. That w...
Called when an application context is popped. This works pretty much the same as: meth: do_teardown_request but for the application context.
def do_teardown_appcontext(self, exc=None): """Called when an application context is popped. This works pretty much the same as :meth:`do_teardown_request` but for the application context. .. versionadded:: 0.9 """ if exc is None: exc = sys.exc_info()[1] ...
The actual WSGI application. This is not implemented in __call__ so that middlewares can be applied without losing a reference to the class. So instead of doing this::
def wsgi_app(self, environ, start_response): """The actual WSGI application. This is not implemented in `__call__` so that middlewares can be applied without losing a reference to the class. So instead of doing this:: app = MyMiddleware(app) It's a better idea to do this ...
Yield unique values in iterable preserving order.
def unique(iterable): """ Yield unique values in iterable, preserving order. """ seen = set() for value in iterable: if not value in seen: seen.add(value) yield value
Place the runtime requirements from pkg_info into metadata.
def handle_requires(metadata, pkg_info, key): """ Place the runtime requirements from pkg_info into metadata. """ may_requires = defaultdict(list) for value in pkg_info.get_all(key): extra_match = EXTRA_RE.search(value) if extra_match: groupdict = extra_match.groupdict() ...
Convert PKG - INFO to a prototype Metadata 2. 0 ( PEP 426 ) dict.
def pkginfo_to_dict(path, distribution=None): """ Convert PKG-INFO to a prototype Metadata 2.0 (PEP 426) dict. The description is included under the key ['description'] rather than being written to a separate file. path: path to PKG-INFO file distribution: optional distutils Distribution() ...
Compose the version predicates for requirement in PEP 345 fashion.
def requires_to_requires_dist(requirement): """Compose the version predicates for requirement in PEP 345 fashion.""" requires_dist = [] for op, ver in requirement.specs: requires_dist.append(op + ver) if not requires_dist: return '' return " (%s)" % ','.join(requires_dist)
Convert. egg - info directory with PKG - INFO to the Metadata 1. 3 aka old - draft Metadata 2. 0 format.
def pkginfo_to_metadata(egg_info_path, pkginfo_path): """ Convert .egg-info directory with PKG-INFO to the Metadata 1.3 aka old-draft Metadata 2.0 format. """ pkg_info = read_pkg_info(pkginfo_path) pkg_info.replace_header('Metadata-Version', '2.0') requires_path = os.path.join(egg_info_path,...
break up a module path to its various parts ( prefix module class method )
def set_possible(self): ''' break up a module path to its various parts (prefix, module, class, method) this uses PEP 8 conventions, so foo.Bar would be foo module with class Bar return -- list -- a list of possible interpretations of the module path (eg, foo.bar can be bar...
return modules that match module_name
def modules(self): """return modules that match module_name""" # since the module has to be importable we go ahead and put the # basepath as the very first path to check as that should minimize # namespace collisions, this is what unittest does also sys.path.insert(0, self.based...
the partial self. class_name will be used to find actual TestCase classes
def classes(self): """the partial self.class_name will be used to find actual TestCase classes""" for module in self.modules(): cs = inspect.getmembers(module, inspect.isclass) class_name = getattr(self, 'class_name', '') class_regex = '' if class_name: ...
return the actual test methods that matched self. method_name
def method_names(self): """return the actual test methods that matched self.method_name""" for c in self.classes(): #ms = inspect.getmembers(c, inspect.ismethod) # http://stackoverflow.com/questions/17019949/ ms = inspect.getmembers(c, lambda f: inspect.ismethod(f) or...
check if name combined with test prefixes or postfixes is found anywhere in the list of basenames
def _find_basename(self, name, basenames, is_prefix=False): """check if name combined with test prefixes or postfixes is found anywhere in the list of basenames :param name: string, the name you're searching for :param basenames: list, a list of basenames to check :param is_pref...
Similar to _find_prefix_paths () but only returns the first match
def _find_prefix_path(self, basedir, prefix): """Similar to _find_prefix_paths() but only returns the first match""" ret = "" for ret in self._find_prefix_paths(basedir, prefix): break if not ret: raise IOError("Could not find prefix {} in path {}".format(prefix,...
Returns true if the passed in path is a test module path
def _is_module_path(self, path): """Returns true if the passed in path is a test module path :param path: string, the path to check, will need to start or end with the module test prefixes or postfixes to be considered valid :returns: boolean, True if a test module path, False other...
Walk all the directories of basedir except hidden directories
def walk(self, basedir): """Walk all the directories of basedir except hidden directories :param basedir: string, the directory to walk :returns: generator, same as os.walk """ system_d = SitePackagesDir() filter_system_d = system_d and os.path.commonprefix([system_d, ba...
given a basedir yield all test modules paths recursively found in basedir that are test modules
def paths(self): ''' given a basedir, yield all test modules paths recursively found in basedir that are test modules return -- generator ''' module_name = getattr(self, 'module_name', '') module_prefix = getattr(self, 'prefix', '') filepath = getattr(sel...
given a filepath like/ base/ path/ to/ module. py this will convert it to path. to. module so it can be imported
def module_path(self, filepath): """given a filepath like /base/path/to/module.py this will convert it to path.to.module so it can be imported""" possible_modbits = re.split('[\\/]', filepath.strip('\\/')) basename = possible_modbits[-1] prefixes = possible_modbits[0:-1] ...
Remove paths in self. paths with confirmation ( unless auto_confirm is True ).
def remove(self, auto_confirm=False): """Remove paths in ``self.paths`` with confirmation (unless ``auto_confirm`` is True).""" if not self._can_uninstall(): return if not self.paths: logger.info( "Can't uninstall '%s'. No files were found to unins...
Rollback the changes previously made by remove ().
def rollback(self): """Rollback the changes previously made by remove().""" if self.save_dir is None: logger.error( "Can't roll back %s; was not uninstalled", self.dist.project_name, ) return False logger.info('Rolling back unin...
Remove temporary save dir: rollback will no longer be possible.
def commit(self): """Remove temporary save dir: rollback will no longer be possible.""" if self.save_dir is not None: rmtree(self.save_dir) self.save_dir = None self._moved_paths = []
Inject default arguments for dump functions.
def _dump_arg_defaults(kwargs): """Inject default arguments for dump functions.""" if current_app: kwargs.setdefault('cls', current_app.json_encoder) if not current_app.config['JSON_AS_ASCII']: kwargs.setdefault('ensure_ascii', False) kwargs.setdefault('sort_keys', current_ap...
Inject default arguments for load functions.
def _load_arg_defaults(kwargs): """Inject default arguments for load functions.""" if current_app: kwargs.setdefault('cls', current_app.json_decoder) else: kwargs.setdefault('cls', JSONDecoder)
Serialize obj to a JSON formatted str by using the application s configured encoder (: attr: ~flask. Flask. json_encoder ) if there is an application on the stack.
def dumps(obj, **kwargs): """Serialize ``obj`` to a JSON formatted ``str`` by using the application's configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an application on the stack. This function can return ``unicode`` strings or ascii-only bytestrings by default which coerce into u...
Like: func: dumps but writes into a file object.
def dump(obj, fp, **kwargs): """Like :func:`dumps` but writes into a file object.""" _dump_arg_defaults(kwargs) encoding = kwargs.pop('encoding', None) if encoding is not None: fp = _wrap_writer_for_text(fp, encoding) _json.dump(obj, fp, **kwargs)
Unserialize a JSON object from a string s by using the application s configured decoder (: attr: ~flask. Flask. json_decoder ) if there is an application on the stack.
def loads(s, **kwargs): """Unserialize a JSON object from a string ``s`` by using the application's configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an application on the stack. """ _load_arg_defaults(kwargs) if isinstance(s, bytes): s = s.decode(kwargs.pop('encoding', ...
Like: func: loads but reads from a file object.
def load(fp, **kwargs): """Like :func:`loads` but reads from a file object. """ _load_arg_defaults(kwargs) if not PY2: fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8') return _json.load(fp, **kwargs)
Works exactly like: func: dumps but is safe for use in <script > tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the |tojson filter which will also mark the result as safe. Due to how this function escapes certain characters this is safe even if used outsi...
def htmlsafe_dumps(obj, **kwargs): """Works exactly like :func:`dumps` but is safe for use in ``<script>`` tags. It accepts the same arguments and returns a JSON string. Note that this is available in templates through the ``|tojson`` filter which will also mark the result as safe. Due to how this fu...
Like: func: htmlsafe_dumps but writes into a file object.
def htmlsafe_dump(obj, fp, **kwargs): """Like :func:`htmlsafe_dumps` but writes into a file object.""" fp.write(unicode(htmlsafe_dumps(obj, **kwargs)))
Creates a: class: ~flask. Response with the JSON representation of the given arguments with an application/ json mimetype. The arguments to this function are the same as to the: class: dict constructor.
def jsonify(*args, **kwargs): """Creates a :class:`~flask.Response` with the JSON representation of the given arguments with an `application/json` mimetype. The arguments to this function are the same as to the :class:`dict` constructor. Example usage:: from flask import jsonify @app...
Implement this method in a subclass such that it returns a serializable object for o or calls the base implementation ( to raise a TypeError ).
def default(self, o): """Implement this method in a subclass such that it returns a serializable object for ``o``, or calls the base implementation (to raise a ``TypeError``). For example, to support arbitrary iterators, you could implement default like this:: def d...
Convert the characters & < > and in string s to HTML - safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string.
def escape(s): """Convert the characters &, <, >, ' and " in string s to HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. Marks return value as markup string. """ if hasattr(s, '__html__'): return s.__html__() return Markup(text_type...
Sets multiple keys and values from a mapping.
def set_many(self, mapping, timeout=None): """Sets multiple keys and values from a mapping. :param mapping: a mapping with the keys/values to set. :param timeout: the cache timeout for the key (if not specified, it uses the default timeout). :returns: Whether all...
Increments the value of a key by delta. If the key does not yet exist it is initialized with delta.
def inc(self, key, delta=1): """Increments the value of a key by `delta`. If the key does not yet exist it is initialized with `delta`. For supporting caches this is an atomic operation. :param key: the key to increment. :param delta: the delta to add. :returns: The ne...
Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else.
def dump_object(self, value): """Dumps an object into a string for redis. By default it serializes integers as regular string and pickle dumps everything else. """ t = type(value) if t in integer_types: return str(value).encode('ascii') return b'!' + pickle.d...
The reversal of: meth: dump_object. This might be callde with None.
def load_object(self, value): """The reversal of :meth:`dump_object`. This might be callde with None. """ if value is None: return None if value.startswith(b'!'): try: return pickle.loads(value[1:]) except pickle.PickleError: ...
Strip req postfix ( - dev 0. 2 etc )
def _strip_postfix(req): """ Strip req postfix ( -dev, 0.2, etc ) """ # FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req
This method generates a dictionary of the query string parameters contained in a given editable URL.
def _build_editable_options(req): """ This method generates a dictionary of the query string parameters contained in a given editable URL. """ regexp = re.compile(r"[\?#&](?P<name>[^&=]+)=(?P<value>[^&=]+)") matched = regexp.findall(req) if matched: ret = dict() for...
Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn + http:// blahblah
def parse_editable(editable_req, default_vcs=None): """Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] """ ...
Creates an InstallRequirement from a name which might be a requirement directory containing setup. py filename or URL.
def from_line( cls, name, comes_from=None, isolated=False, options=None, wheel_cache=None): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ from pip.index import Link if is...
Ensure that if a link can be found for this that it is found.
def populate_link(self, finder, upgrade): """Ensure that if a link can be found for this, that it is found. Note that self.link may still be None - if Upgrade is False and the requirement is already installed. """ if self.link is None: self.link = finder.find_require...
Move self. _temp_build_dir to self. _ideal_build_dir/ self. req. name
def _correct_build_location(self): """Move self._temp_build_dir to self._ideal_build_dir/self.req.name For some requirements (e.g. a path to a directory), the name of the package is not available until we run egg_info, so the build_location will return a temporary directory and store th...
Ensure that a source_dir is set.
def ensure_has_source_dir(self, parent_dir): """Ensure that a source_dir is set. This will create a temporary build dir if the name of the requirement isn't known yet. :param parent_dir: The ideal pip parent_dir for the source_dir. Generally src_dir for editables and build_...
Remove the source files from this requirement if they are marked for deletion
def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.source_dir and os.path.exists( os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)): logger.debug('Removing source in %s', self.source...
Return a pkg_resources. Distribution built from self. egg_info_path
def get_dist(self): """Return a pkg_resources.Distribution built from self.egg_info_path""" egg_info = self.egg_info_path('').rstrip('/') base_dir = os.path.dirname(egg_info) metadata = pkg_resources.PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(e...
Extract metadata from filenames. Extracts the 4 metadataitems needed ( name version pyversion arch ) from the installer filename and the name of the egg - info directory embedded in the zipfile ( if any ).
def parse_info(wininfo_name, egginfo_name): """Extract metadata from filenames. Extracts the 4 metadataitems needed (name, version, pyversion, arch) from the installer filename and the name of the egg-info directory embedded in the zipfile (if any). The egginfo filename has the format:: ...
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.
def is_internal_attribute(obj, attr): """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. >...
This is the same as accessing: attr: stream with the difference that if it finds cached data from calling: meth: get_data first it will create a new stream out of the cached data.
def _get_stream_for_parsing(self): """This is the same as accessing :attr:`stream` with the difference that if it finds cached data from calling :meth:`get_data` first it will create a new stream out of the cached data. .. versionadded:: 0.9.3 """ cached_data = getattr(s...
This reads the buffered incoming data from the client into one bytestring. By default this is cached but that behavior can be changed by setting cache to False.
def get_data(self, cache=True, as_text=False, parse_form_data=False): """This reads the buffered incoming data from the client into one bytestring. By default this is cached but that behavior can be changed by setting `cache` to `False`. Usually it's a bad idea to call this method with...
This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary.
def get_wsgi_headers(self, environ): """This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the loc...
r Sometimes you get an URL by a user that just isn t a real URL because it contains unsafe characters like and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user:
def url_fix(s, charset='utf-8'): r"""Sometimes you get an URL by a user that just isn't a real URL because it contains unsafe characters like ' ' and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: >>> url_fix(u'http://de.wikipedia.org/wi...
r Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always uses utf - 8 URLs internally because this is what browsers and HTTP do as well. In some places where it accepts an URL it also accepts a unicode IRI and converts it into a URI.
def iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False): r""" Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always uses utf-8 URLs internally because this is what browsers and HTTP do as well. In some places where it accepts an URL it also accepts a unicode IRI...
r Return full path to the user - specific cache dir for this application.
def user_cache_dir(appname): r""" Return full path to the user-specific cache dir for this application. "appname" is the name of application. Typical user cache directories are: Mac OS X: ~/Library/Caches/<AppName> Unix: ~/.cache/<AppName> (XDG default) Windows: ...
Return full path to the user - specific data dir for this application.
def user_data_dir(appname, roaming=False): """ Return full path to the user-specific data dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default False) can be set True to use the Windows ...
Return full path to the user - specific log dir for this application.
def user_log_dir(appname): """ Return full path to the user-specific log dir for this application. "appname" is the name of application. If None, just the system directory is returned. Typical user cache directories are: Mac OS X: ~/Library/Logs/<AppName> Unix: ...
Return full path to the user - specific config dir for this application.
def user_config_dir(appname, roaming=True): """Return full path to the user-specific config dir for this application. "appname" is the name of application. If None, just the system directory is returned. "roaming" (boolean, default True) can be set False to not use the Windo...
Return a list of potential user - shared config dirs for this application.
def site_config_dirs(appname): """Return a list of potential user-shared config dirs for this application. "appname" is the name of application. Typical user config directories are: Mac OS X: /Library/Application Support/<AppName>/ Unix: /etc or $XDG_CONFIG_DIRS[i]/<AppName>/ f...
This iterates over all relevant Python files. It goes through all loaded files from modules all files in folders of already loaded modules as well as all files reachable through a package.
def _iter_module_files(): """This iterates over all relevant Python files. It goes through all loaded files from modules, all files in folders of already loaded modules as well as all files reachable through a package. """ # The list call is necessary on Python 3 in case the module # dictionary...
Spawn a new Python interpreter with the same arguments as this one but running the reloader thread.
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one, but running the reloader thread. """ while 1: _log('info', ' * Restarting with %s' % self.name) args = [sys.executable] + sys.argv new_environ = os....
Wrapper around six. text_type to convert None to empty string
def to_text(s, blank_if_none=True): """Wrapper around six.text_type to convert None to empty string""" if s is None: if blank_if_none: return "" else: return None elif isinstance(s, text_type): return s else: return text_type(s)
Return an existing CA bundle path or None
def find_ca_bundle(): """Return an existing CA bundle path, or None""" if os.name=='nt': return get_win_certfile() else: for cert_path in cert_paths: if os.path.isfile(cert_path): return cert_path try: return pkg_resources.resource_filename('certifi', ...
Parse a string or file - like object into a tree
def parse(doc, treebuilder="etree", encoding=None, namespaceHTMLElements=True): """Parse a string or file-like object into a tree""" tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parse(doc, encoding=encoding)
Parse a HTML document into a well - formed tree
def parse(self, stream, encoding=None, parseMeta=True, useChardet=True): """Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, t...
Parse a HTML fragment into a well - formed tree fragment
def parseFragment(self, stream, container="div", encoding=None, parseMeta=False, useChardet=True): """Parse a HTML fragment into a well-formed tree fragment container - name of the element we're setting the innerHTML property if set to None, default to 'div' strea...
Generic RCDATA/ RAWTEXT Parsing algorithm contentType - RCDATA or RAWTEXT
def parseRCDataRawtext(self, token, contentType): """Generic RCDATA/RAWTEXT Parsing algorithm contentType - RCDATA or RAWTEXT """ assert contentType in ("RAWTEXT", "RCDATA") self.tree.insertElement(token) if contentType == "RAWTEXT": self.tokenizer.state = s...
pass in a word string that you would like to see probable matches for.
def translate(self, word): """ pass in a word string that you would like to see probable matches for. """ if (word not in self.transmissions): raise NoMatchError('no matches found') else: trans = self.transmissions[word] # print out a s...
this converts the readin lines from sys to useable format returns list of token and dict of tokens
def convertArgsToTokens(self, data): """ this converts the readin lines from sys to useable format, returns list of token and dict of tokens """ tdict = [] tokens = [] d = open(data, 'r') for line in d.readlines(): tdict.append(line.r...
get all probable matches and then initialize t ( f|e )
def initTef(self): ''' get all probable matches and then initialize t(f|e) ''' probs = {} transmissions = {} # go through each german word for word in self.en_words: word_poss = [] # if word in sentence.. then for sent...
Iterate through all transmissions of english to foreign words. keep count of repeated occurences do until convergence set count ( e|f ) to 0 for all e f set total ( f ) to 0 for all f for all sentence pairs ( e_s f_s ) set total_s ( e ) = 0 for all e for all words e in e_s for all words f in f_s total_s ( e ) + = t ( e...
def iterateEM(self, count): ''' Iterate through all transmissions of english to foreign words. keep count of repeated occurences do until convergence set count(e|f) to 0 for all e,f set total(f) to 0 for all f for all sentence pairs (e_s,f_s) ...
Bind and activate HTTP server.
def bind(self): """Bind and activate HTTP server.""" HTTPServer.__init__(self, (self.host, self.port), HTTPRequestHandler) self.port = self.server_port
Report startup info to stdout.
def report(self): """Report startup info to stdout.""" print( self.report_message.format( service=self.service, host=self.host, port=self.port, ) ) sys.stdout.flush()
Creates an SSL key for development. This should be used instead of the adhoc key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN *. host/ CN = host.
def make_ssl_devcert(base_path, host=None, cn=None): """Creates an SSL key for development. This should be used instead of the ``'adhoc'`` key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it wi...
Loads bytecode from a file or file like object.
def load_bytecode(self, f): """Loads bytecode from a file or file like object.""" # make sure the magic header is correct magic = f.read(len(bc_magic)) if magic != bc_magic: self.reset() return # the source code of the file changed, we need to reload ...
Convert keyword args to a dictionary of stylesheet parameters. XSL stylesheet parameters must be XPath expressions i. e.:
def stylesheet_params(**kwargs): """Convert keyword args to a dictionary of stylesheet parameters. XSL stylesheet parameters must be XPath expressions, i.e.: * string expressions, like "'5'" * simple (number) expressions, like "5" * valid XPath expressions, like "/a/b/text()" This function con...
Return a copy of paramsDict updated with kwargsDict entries wrapped as stylesheet arguments. kwargsDict entries with a value of None are ignored.
def _stylesheet_param_dict(paramsDict, kwargsDict): """Return a copy of paramsDict, updated with kwargsDict entries, wrapped as stylesheet arguments. kwargsDict entries with a value of None are ignored. """ # beware of changing mutable default arg paramsDict = dict(paramsDict) for k, v in kw...
Extract embedded schematron schema from non - schematron host schema. This method will only be called by __init__ if the given schema document is not a schematron schema by itself. Must return a schematron schema document tree or None.
def _extract(self, element): """Extract embedded schematron schema from non-schematron host schema. This method will only be called by __init__ if the given schema document is not a schematron schema by itself. Must return a schematron schema document tree or None. """ sc...
Return the name of the version control backend if found at given location e. g. vcs. get_backend_name (/ path/ to/ vcs/ checkout )
def get_backend_name(self, location): """ Return the name of the version control backend if found at given location, e.g. vcs.get_backend_name('/path/to/vcs/checkout') """ for vc_type in self._registry.values(): logger.debug('Checking in %s for %s (%s)...', ...
posix absolute paths start with os. path. sep win32 ones ones start with drive ( like c: \\ folder )
def _is_local_repository(self, repo): """ posix absolute paths start with os.path.sep, win32 ones ones start with drive (like c:\\folder) """ drive, tail = os.path.splitdrive(repo) return repo.startswith(os.path.sep) or drive
Returns ( url revision ) where both are strings
def get_info(self, location): """ Returns (url, revision), where both are strings """ assert not location.rstrip('/').endswith(self.dirname), \ 'Bad directory: %s' % location return self.get_url(location), self.get_revision(location)
Clean up current location and download the url repository ( and vcs infos ) into location
def unpack(self, location): """ Clean up current location and download the url repository (and vcs infos) into location """ if os.path.exists(location): rmtree(location) self.obtain(location)
Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the VCS command name and checks that the VCS is available
def run_command(self, cmd, show_stdout=True, cwd=None, raise_on_returncode=True, command_level=logging.DEBUG, command_desc=None, extra_environ=None): """ Run a VCS subcommand This is simply a wrapper around call_subprocess that adds the...
Return implementation version.
def get_impl_ver(): """Return implementation version.""" impl_ver = sysconfig.get_config_var("py_version_nodot") if not impl_ver: impl_ver = ''.join(map(str, sys.version_info[:2])) return impl_ver
Return a list of supported tags for each version specified in versions.
def get_supported(versions=None): """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. """ supported = [] # Versions must be...
Return the real host for the given WSGI environment. This first checks the X - Forwarded - Host header then the normal Host header and finally the SERVER_NAME environment variable ( using the first one it finds ).
def get_host(environ, trusted_hosts=None): """Return the real host for the given WSGI environment. This first checks the `X-Forwarded-Host` header, then the normal `Host` header, and finally the `SERVER_NAME` environment variable (using the first one it finds). Optionally it verifies that the host is ...
Yield egg or source distribution objects based on basename
def distros_for_location(location, basename, metadata=None): """Yield egg or source distribution objects based on basename""" if basename.endswith('.egg.zip'): basename = basename[:-4] # strip the .zip if basename.endswith('.egg') and '-' in basename: # only one, unambiguous interpretatio...
Find rel = homepage and rel = download links in page yielding URLs
def find_external_links(url, page): """Find rel="homepage" and rel="download" links in `page`, yielding URLs""" for match in REL.finditer(page): tag, rel = match.groups() rels = set(map(str.strip, rel.lower().split(','))) if 'homepage' in rels or 'download' in rels: for matc...
A function compatible with Python 2. 3 - 3. 3 that will encode auth from a URL suitable for an HTTP header. >>> str ( _encode_auth ( username%3Apassword )) dXNlcm5hbWU6cGFzc3dvcmQ =
def _encode_auth(auth): """ A function compatible with Python 2.3-3.3 that will encode auth from a URL suitable for an HTTP header. >>> str(_encode_auth('username%3Apassword')) 'dXNlcm5hbWU6cGFzc3dvcmQ=' Long auth strings should not cause a newline to be inserted. >>> long_auth = 'username:...
Read a local path with special support for directories
def local_open(url): """Read a local path, with special support for directories""" scheme, server, path, param, query, frag = urlparse(url) filename = url2pathname(path) if os.path.isfile(filename): return urllib2.urlopen(url) elif path.endswith('/') and os.path.isdir(filename): file...
Construct a ( possibly null ) ContentChecker from a URL
def from_url(cls, url): "Construct a (possibly null) ContentChecker from a URL" fragment = urlparse(url)[-1] if not fragment: return ContentChecker() match = cls.pattern.search(fragment) if not match: return ContentChecker() return cls(**match.grou...
Evaluate a URL as a possible download and maybe retrieve it
def process_url(self, url, retrieve=False): """Evaluate a URL as a possible download, and maybe retrieve it""" if url in self.scanned_urls and not retrieve: return self.scanned_urls[url] = True if not URL_SCHEME(url): self.process_filename(url) return ...
Return a list of supported tags for each version specified in versions.
def get_supported(versions=None, noarch=False): """Return a list of supported tags for each version specified in `versions`. :param versions: a list of string versions, of the form ["33", "32"], or None. The first version will be assumed to support our ABI. """ supported = [] # Version...
Remove duplicate entries from sys. path along with making them absolute
def removeduppaths(): """ Remove duplicate entries from sys.path along with making them absolute""" # This ensures that the initial path provided by the interpreter contains # only absolute pathnames, even if we're running from the build directory. L = [] known_paths = set() for dir in sys.p...
Append./ build/ lib. <platform > in case we re running in the build dir ( especially for Guido: - )
def addbuilddir(): """Append ./build/lib.<platform> in case we're running in the build dir (especially for Guido :-)""" from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version) if hasattr(sys, 'gettotalrefcount'): s += '-pydebug' s = os.path.join(os...