INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Preload all top-level definitions.
def preload_defs(self): """Preload all top-level definitions.""" for d in (self.module.search("grouping") + self.module.search("typedef")): uname, dic = self.unique_def_name(d) self.install_def(uname, d, dic)
Return `name` prepended with correct prefix. If the name is already prefixed, the prefix may be translated to the value obtained from `self.module_prefixes`. Unmodified `name` is returned if we are inside a global grouping.
def add_prefix(self, name, stmt): """Return `name` prepended with correct prefix. If the name is already prefixed, the prefix may be translated to the value obtained from `self.module_prefixes`. Unmodified `name` is returned if we are inside a global grouping. """ if se...
Return (prefixed) node name of `stmt`. The result is prefixed with the local prefix unless we are inside a global grouping.
def qname(self, stmt): """Return (prefixed) node name of `stmt`. The result is prefixed with the local prefix unless we are inside a global grouping. """ if self.gg_level: return stmt.arg return self.prefix_stack[-1] + ":" + stmt.arg
Add DC element `name` containing `text` to `parent`.
def dc_element(self, parent, name, text): """Add DC element `name` containing `text` to `parent`.""" if self.dc_uri in self.namespaces: dcel = SchemaNode(self.namespaces[self.dc_uri] + ":" + name, text=text) parent.children.insert(0,dcel)
Return default value for `stmt` node. `refd` is a dictionary of applicable refinements that is constructed in the `process_patches` method.
def get_default(self, stmt, refd): """Return default value for `stmt` node. `refd` is a dictionary of applicable refinements that is constructed in the `process_patches` method. """ if refd["default"]: return refd["default"] defst = stmt.search_one("defau...
Mangle the name of `stmt` (typedef or grouping). Return the mangled name and dictionary where the definition is to be installed. The `inrpc` flag indicates when we are inside an RPC, in which case the name gets the "__rpc" suffix.
def unique_def_name(self, stmt, inrpc=False): """Mangle the name of `stmt` (typedef or grouping). Return the mangled name and dictionary where the definition is to be installed. The `inrpc` flag indicates when we are inside an RPC, in which case the name gets the "__rpc" suffix. ...
Add patch corresponding to `augref` to `pset`. `augref` must be either 'augment' or 'refine' statement.
def add_patch(self, pset, augref): """Add patch corresponding to `augref` to `pset`. `augref` must be either 'augment' or 'refine' statement. """ try: path = [ self.add_prefix(c, augref) for c in augref.arg.split("/") if c ] except KeyError: ...
Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants.
def apply_augments(self, auglist, p_elem, pset): """Handle substatements of augments from `auglist`. The augments are applied in the context of `p_elem`. `pset` is a patch set containing patches that may be applicable to descendants. """ for a in auglist: pa...
Pick the most recent revision date. `r_stmts` is a list of 'revision' statements.
def current_revision(self, r_stmts): """Pick the most recent revision date. `r_stmts` is a list of 'revision' statements. """ cur = max([[int(p) for p in r.arg.split("-")] for r in r_stmts]) return "%4d-%02d-%02d" % tuple(cur)
Add <a:documentation> with `docstring` to `p_elem`.
def insert_doc(self, p_elem, docstring): """Add <a:documentation> with `docstring` to `p_elem`.""" dtag = self.namespaces[self.a_uri] + ":documentation" elem = SchemaNode(dtag, text=docstring) p_elem.annots.append(elem)
Install definition `name` into the appropriate dictionary. `dstmt` is the definition statement ('typedef' or 'grouping') that is to be mapped to a RELAX NG named pattern '<define name="`name`">'. `def_map` must be either `self.local_defs` or `self.global_defs`. `interleave` determines t...
def install_def(self, name, dstmt, def_map, interleave=False): """Install definition `name` into the appropriate dictionary. `dstmt` is the definition statement ('typedef' or 'grouping') that is to be mapped to a RELAX NG named pattern '<define name="`name`">'. `def_map` must be either ...
Append YIN representation of extension statement `stmt`.
def rng_annotation(self, stmt, p_elem): """Append YIN representation of extension statement `stmt`.""" ext = stmt.i_extension prf, extkw = stmt.raw_keyword (modname,rev)=stmt.i_module.i_prefixes[prf] prefix = self.add_namespace( statements.modulename_to_module(self.mo...
Propagate occurence `value` to `node` and its ancestors. Occurence values are defined and explained in the SchemaNode class.
def propagate_occur(self, node, value): """Propagate occurence `value` to `node` and its ancestors. Occurence values are defined and explained in the SchemaNode class. """ while node.occur < value: node.occur = value if node.name == "define": ...
Process patches for data node `name` from `pset`. `stmt` provides the context in YANG and `elem` is the parent element in the output schema. Refinements adding documentation and changing the config status are immediately applied. The returned tuple consists of: - a dictionary ...
def process_patches(self, pset, stmt, elem, altname=None): """Process patches for data node `name` from `pset`. `stmt` provides the context in YANG and `elem` is the parent element in the output schema. Refinements adding documentation and changing the config status are immediately appl...
Return pair of (min,max)-elements values for `stmt`. `stmt` must be a 'list' or 'leaf-list'. Applicable refinements from `refine_dict` are also taken into account.
def get_minmax(self, stmt, refine_dict): """Return pair of (min,max)-elements values for `stmt`. `stmt` must be a 'list' or 'leaf-list'. Applicable refinements from `refine_dict` are also taken into account. """ minel = refine_dict["min-elements"] maxel = refine_dict["ma...
Find schema nodes under `stmt`, also in used groupings. `names` is a list with qualified names of the schema nodes to look up. All 'uses'/'grouping' pairs between `stmt` and found schema nodes are marked for expansion.
def lookup_expand(self, stmt, names): """Find schema nodes under `stmt`, also in used groupings. `names` is a list with qualified names of the schema nodes to look up. All 'uses'/'grouping' pairs between `stmt` and found schema nodes are marked for expansion. """ if not ...
Handle types with 'range' or 'length' restrictions. `tchain` is the chain of type definitions from which the ranges may need to be extracted. `rangekw` is the statement keyword determining the range type (either 'range' or 'length'). `gen_data` is a function that generates the o...
def type_with_ranges(self, tchain, p_elem, rangekw, gen_data): """Handle types with 'range' or 'length' restrictions. `tchain` is the chain of type definitions from which the ranges may need to be extracted. `rangekw` is the statement keyword determining the range type (either 'range' o...
Return list of ranges defined in `tchain`. `kw` is the statement keyword determining the type of the range, i.e. 'range' or 'length'. `tchain` is the chain of type definitions from which the resulting range is obtained. The returned value is a list of tuples containing the segments ...
def get_ranges(self, tchain, kw): """Return list of ranges defined in `tchain`. `kw` is the statement keyword determining the type of the range, i.e. 'range' or 'length'. `tchain` is the chain of type definitions from which the resulting range is obtained. The returned value is...
Return list of <param>s corresponding to range `ran`. `kw` is the statement keyword determining the type of the range, i.e. 'range' or 'length'. `ran` is the internal representation of a range as constructed by the `get_ranges` method.
def range_params(self, ran, kw): """Return list of <param>s corresponding to range `ran`. `kw` is the statement keyword determining the type of the range, i.e. 'range' or 'length'. `ran` is the internal representation of a range as constructed by the `get_ranges` method. ...
Run handler method for statement `stmt`. `p_elem` is the parent node in the output schema. `pset` is the current "patch set" - a dictionary with keys being QNames of schema nodes at the current level of hierarchy for which (or descendants thereof) any pending patches exist. The values ...
def handle_stmt(self, stmt, p_elem, pset={}): """ Run handler method for statement `stmt`. `p_elem` is the parent node in the output schema. `pset` is the current "patch set" - a dictionary with keys being QNames of schema nodes at the current level of hierarchy for which ...
Handle all substatements of `stmt`.
def handle_substmts(self, stmt, p_elem, pset={}): """Handle all substatements of `stmt`.""" for sub in stmt.substmts: self.handle_stmt(sub, p_elem, pset)
Map `stmt` to a NETMOD-specific attribute. The name of the attribute is the same as the 'keyword' of `stmt`.
def nma_attribute(self, stmt, p_elem, pset=None): """Map `stmt` to a NETMOD-specific attribute. The name of the attribute is the same as the 'keyword' of `stmt`. """ att = "nma:" + stmt.keyword if att not in p_elem.attr: p_elem.attr[att] = stmt.arg
Handle ``type`` statement. Built-in types are handled by one of the specific type callback methods defined below.
def type_stmt(self, stmt, p_elem, pset): """Handle ``type`` statement. Built-in types are handled by one of the specific type callback methods defined below. """ typedef = stmt.i_typedef if typedef and not stmt.i_is_derived: # just ref uname, dic = self.uniqu...
Handle ``enumeration`` and ``union`` types.
def choice_type(self, tchain, p_elem): """Handle ``enumeration`` and ``union`` types.""" elem = SchemaNode.choice(p_elem, occur=2) self.handle_substmts(tchain[0], elem)
Handle types that are simply mapped to RELAX NG.
def mapped_type(self, tchain, p_elem): """Handle types that are simply mapped to RELAX NG.""" SchemaNode("data", p_elem).set_attr("type", self.datatype_map[tchain[0].arg])
Handle numeric types.
def numeric_type(self, tchain, p_elem): """Handle numeric types.""" typ = tchain[0].arg def gen_data(): elem = SchemaNode("data").set_attr("type", self.datatype_map[typ]) if typ == "decimal64": fd = tchain[0].search_one("fraction-digits").arg ...
Called by pyang plugin framework at to initialize the plugin.
def pyang_plugin_init(): """Called by pyang plugin framework at to initialize the plugin.""" # Register the plugin plugin.register_plugin(MDPlugin()) # Register that we handle extensions from the YANG module # 'ietf-yang-metadata' grammar.register_extension_module(md_module_name) # Regist...
Use by plugins to add grammar for an extension statement.
def add_stmt(stmt, arg_rules): """Use by plugins to add grammar for an extension statement.""" (arg, rules) = arg_rules stmt_map[stmt] = (arg, rules)
Use by plugins to add extra rules to the existing rules for a statement.
def add_to_stmts_rules(stmts, rules): """Use by plugins to add extra rules to the existing rules for a statement.""" def is_rule_less_than(ra, rb): rka = ra[0] rkb = rb[0] if not util.is_prefixed(rkb): # old rule is non-prefixed; append new rule after return F...
Validate the statement hierarchy according to the grammar. Return True if module is valid, False otherwise.
def chk_module_statements(ctx, module_stmt, canonical=False): """Validate the statement hierarchy according to the grammar. Return True if module is valid, False otherwise. """ return chk_statement(ctx, module_stmt, top_stmts, canonical)
Validate `stmt` according to `grammar`. Marks each statement in the hierearchy with stmt.is_grammatically_valid, which is a boolean. Return True if stmt is valid, False otherwise.
def chk_statement(ctx, stmt, grammar, canonical=False): """Validate `stmt` according to `grammar`. Marks each statement in the hierearchy with stmt.is_grammatically_valid, which is a boolean. Return True if stmt is valid, False otherwise. """ n = len(ctx.errors) if canonical == True: ...
Match stmt against the spec. Return None | spec' spec' is an updated spec with the matching spec consumed
def _match_stmt(ctx, stmt, specs, canonical): """Match stmt against the spec. Return None | spec' spec' is an updated spec with the matching spec consumed """ (spec, canspec) = specs i = 0 while i < len(spec): (keywd, occurance) = spec[i] if keywd == '$any': retu...
Sort all `stmts` in the canonical order defined by `keyword`. Return the sorted list. The `stmt` list is not modified. If `keyword` does not have a canonical order, the list is returned as is.
def sort_canonical(keyword, stmts): """Sort all `stmts` in the canonical order defined by `keyword`. Return the sorted list. The `stmt` list is not modified. If `keyword` does not have a canonical order, the list is returned as is. """ try: (_arg_type, subspec) = stmt_map[keyword] ...
Step : AbbreviatedStep PredicateList
def p_step_7(p): 'Step : AbbreviatedStep PredicateList' if p[1][1] == 'self': a = "." x = "self::node()" else: a = ".." x = "parent::node()" msg = "%s[<pred>] is illegal syntax. use %s[<pred>] instead," % (a, x) raise xpath_lexer.XPathError(msg, 1, 1)
AbbreviatedRelativeLocationPath : RelativeLocationPath DOUBLESLASH Step
def p_abbrev_rel_loc_path(p): 'AbbreviatedRelativeLocationPath : RelativeLocationPath DOUBLESLASH Step' p[0] = list(p[1]) p[0].append(_expand_double_slash()) p[0].append(p[3])
PathExpr : FilterExpr DOUBLESLASH RelativeLocationPath
def p_path_expr_4(p): 'PathExpr : FilterExpr DOUBLESLASH RelativeLocationPath' p[0] = [p[1]] p[0].append(_expand_double_slash()) p[0].extend(p[3])
Return a list of tokens, or throw SyntaxError on failure.
def scan(s): """Return a list of tokens, or throw SyntaxError on failure. """ line = 1 linepos = 1 pos = 0 toks = [] while pos < len(s): matched = False for (tokname, r) in patterns: m = r.match(s, pos) if m is not None: # found a match...
Return a list of advertised YANG module names with revisions. Avoid repeated modules.
def yang_modules(self): """ Return a list of advertised YANG module names with revisions. Avoid repeated modules. """ res = {} for c in self.capabilities: m = c.parameters.get("module") if m is None or m in res: continue res[m] = c.par...
Return list of features declared for module `yam`.
def get_features(self, yam): """Return list of features declared for module `yam`.""" mcap = [ c for c in self.capabilities if c.parameters.get("module", None) == yam ][0] if not mcap.parameters.get("features"): return [] return mcap.parameters["features"].split(",")
Return dictionary of non-YANG capabilities. Only capabilities from the `CAPABILITIES` dictionary are taken into account.
def registered_capabilities(self): """Return dictionary of non-YANG capabilities. Only capabilities from the `CAPABILITIES` dictionary are taken into account. """ return dict ([ (CAPABILITIES[c.id],c) for c in self.capabilities if c.id in CAPABILITIES ])
Guess YANG/YIN format If the first non-whitespace character is '<' then it is XML. Return 'yang' or 'yin
def guess_format(text): """Guess YANG/YIN format If the first non-whitespace character is '<' then it is XML. Return 'yang' or 'yin'""" format = 'yang' i = 0 while i < len(text) and text[i].isspace(): i += 1 if i < len(text): if text[i] == '<': format = 'yin' ...
Return a new list with x removed from xs
def listsdelete(x, xs): """Return a new list with x removed from xs""" i = xs.index(x) return xs[:i] + xs[(i+1):]
Return a dictionary with unique prefixes for modules in `context`. Keys are 'module' statements and values are prefixes, disambiguated where necessary.
def unique_prefixes(context): """Return a dictionary with unique prefixes for modules in `context`. Keys are 'module' statements and values are prefixes, disambiguated where necessary. """ res = {} for m in context.modules.values(): if m.keyword == "submodule": continue prf = ne...
Change the installation prefix where necessary.
def preprocess_files(self, prefix): """Change the installation prefix where necessary. """ if prefix is None: return files = ("bin/yang2dsdl", "man/man1/yang2dsdl.1", "pyang/plugins/jsonxsl.py") regex = re.compile("^(.*)/usr/local(.*)$") ...
Parse a module text and add the module data to the context `ref` is a string which is used to identify the source of the text for the user. used in error messages `text` is the raw text data `format` is one of 'yang' or 'yin'. Returns the parsed and validated module on s...
def add_module(self, ref, text, format=None, expect_modulename=None, expect_revision=None, expect_failure_error=True): """Parse a module text and add the module data to the context `ref` is a string which is used to identify the source of the text for...
Remove a module from the context
def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
Return the module if it exists in the context
def get_module(self, modulename, revision=None): """Return the module if it exists in the context""" if revision is None and modulename in self.revs: (revision, _handle) = self._get_latest_rev(self.revs[modulename]) if revision is not None: if (modulename,revision) in sel...
Searches for a module named `modulename` in the repository If the module is found, it is added to the context. Returns the module if found, and None otherwise
def search_module(self, pos, modulename, revision=None): """Searches for a module named `modulename` in the repository If the module is found, it is added to the context. Returns the module if found, and None otherwise""" if modulename not in self.revs: # this module doesn'...
Searches for a module named `modulename` in the repository The module is just read, and not compiled at all. Returns the module if found, and None otherwise
def read_module(self, modulename, revision=None, extra={}): """Searches for a module named `modulename` in the repository The module is just read, and not compiled at all. Returns the module if found, and None otherwise""" if modulename not in self.revs: # this module doesn...
Initialize the plugin framework
def init(plugindirs=[]): """Initialize the plugin framework""" # initialize the builtin plugins from .translators import yang,yin,dsdl yang.pyang_plugin_init() yin.pyang_plugin_init() dsdl.pyang_plugin_init() # initialize installed plugins for ep in pkg_resources.iter_entry_points(grou...
Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.
def split_qname(qname): """Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.""" res = qname.split(YinParser.ns_sep) if len(res) == 1: # no namespace return None, res[0] else: ...
Parse the string `text` containing a YIN (sub)module. Return a Statement on success or None on failure.
def parse(self, ctx, ref, text): """Parse the string `text` containing a YIN (sub)module. Return a Statement on success or None on failure. """ self.ctx = ctx self.pos = error.Position(ref) self.top = None self.top_element = None self.uri = None ...
Check for unknown attributes.
def check_attr(self, pos, attrs): """Check for unknown attributes.""" for at in attrs: (ns, local_name) = self.split_qname(at) if ns is None: error.err_add(self.ctx.errors, pos, 'UNEXPECTED_ATTRIBUTE', local_name) elif ns...
Search for a defintion with `keyword` `name` Search the module and its submodules.
def search_definition(self, module, keyword, arg): """Search for a defintion with `keyword` `name` Search the module and its submodules.""" r = module.search_one(keyword, arg) if r is not None: return r for i in module.search('include'): modulename = i.arg...
Heuristically pretty print a path argument
def emit_path_arg(keywordstr, arg, fd, indent, max_line_len, line_len, eol): """Heuristically pretty print a path argument""" quote = '"' arg = escape_str(arg) if not(need_new_line(max_line_len, line_len, arg)): fd.write(" " + quote + arg + quote) return False ## FIXME: we should...
Heuristically pretty print the argument string with double quotes
def emit_arg(keywordstr, stmt, fd, indent, indentstep, max_line_len, line_len): """Heuristically pretty print the argument string with double quotes""" arg = escape_str(stmt.arg) lines = arg.splitlines(True) if len(lines) <= 1: if len(arg) > 0 and arg[-1] == '\n': arg = arg[:-1] + r'...
Main control function. Set up the top-level parts of the sample document, then process recursively all nodes in all data trees, and finally emit the sample XML document.
def emit(self, ctx, modules, fd): """Main control function. Set up the top-level parts of the sample document, then process recursively all nodes in all data trees, and finally emit the sample XML document. """ if ctx.opts.sample_path is not None: path = ctx....
Proceed with all children of `node`.
def process_children(self, node, elem, module, path, omit=[]): """Proceed with all children of `node`.""" for ch in node.i_children: if ch not in omit and (ch.i_config or self.doctype == "data"): self.node_handler.get(ch.keyword, self.ignore)( ch, elem, mo...
Create a sample container element and proceed with its children.
def container(self, node, elem, module, path): """Create a sample container element and proceed with its children.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: pres = node.search_one("presence") ...
Create a sample leaf element.
def leaf(self, node, elem, module, path): """Create a sample leaf element.""" if node.i_default is None: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment( ...
Create a sample anyxml element.
def anyxml(self, node, elem, module, path): """Create a sample anyxml element.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment(" anyxml "))
Create sample entries of a list.
def list(self, node, elem, module, path): """Create sample entries of a list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return for kn in node.i_key: self.node_handler.get(kn.keyword, self.ignore)( kn, nel, ...
Create sample entries of a leaf-list.
def leaf_list(self, node, elem, module, path): """Create sample entries of a leaf-list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return minel = node.search_one("min-elements") self.add_copies(node, elem, nel, minel) s...
Create element under `parent`. Declare new namespace if necessary.
def sample_element(self, node, parent, module, path): """Create element under `parent`. Declare new namespace if necessary. """ if path is None: return parent, module, None elif path == []: # GO ON pass else: if node.arg ==...
Add appropriate number of `elem` copies to `parent`.
def add_copies(self, node, parent, elem, minel): """Add appropriate number of `elem` copies to `parent`.""" rep = 0 if minel is None else int(minel.arg) - 1 for i in range(rep): parent.append(copy.deepcopy(elem))
Add list annotation to `elem`.
def list_comment(self, node, elem, minel): """Add list annotation to `elem`.""" lo = "0" if minel is None else minel.arg maxel = node.search_one("max-elements") hi = "" if maxel is None else maxel.arg elem.insert(0, etree.Comment( " # entries: %s..%s " % (lo, hi))) ...
Called by pyang plugin framework at to initialize the plugin.
def pyang_plugin_init(): """Called by pyang plugin framework at to initialize the plugin.""" # Register the plugin plugin.register_plugin(RESTCONFPlugin()) # Register that we handle extensions from the YANG module 'ietf-restconf' grammar.register_extension_module(restconf_module_name) yd = (r...
Normalizes string, removes non-alpha characters, and converts spaces to ``separator`` character
def slugify(value, separator='-', max_length=0, word_boundary=False, entities=True, decimal=True, hexadecimal=True): '''Normalizes string, removes non-alpha characters, and converts spaces to ``separator`` character ''' value = normalize('NFKD', to_string(value, 'utf-8', 'ignore')) if un...
Truncate a string
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ value = value.strip(separator) if not max_length: return value if len(value) < max_length: return value if not word_boundaries: return value[:max_length].strip(separat...
Called by the protocol consumer
def get(self): '''Called by the protocol consumer''' if self._current: return self._resume(self._current, False) else: return self._get(None)
Multi bulk encoding for list/tuple ``args``
def multi_bulk(self, args): '''Multi bulk encoding for list/tuple ``args`` ''' return null_array if args is None else b''.join(self._pack(args))
Packs pipeline commands into bytes.
def pack_pipeline(self, commands): '''Packs pipeline commands into bytes.''' return b''.join( starmap(lambda *args: b''.join(self._pack_command(args)), (a for a, _ in commands)))
Get the latest pypi release
def pypi_release(self): """Get the latest pypi release """ meta = self.distribution.metadata pypi = ServerProxy(self.pypi_index_url) releases = pypi.package_releases(meta.name) if releases: return next(iter(sorted(releases, reverse=True)))
Check if thread is the main thread. If ``thread`` is not supplied check the current thread
def is_mainthread(thread=None): '''Check if thread is the main thread. If ``thread`` is not supplied check the current thread ''' thread = thread if thread is not None else current_thread() return isinstance(thread, threading._MainThread)
Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary
def process_data(name=None): '''Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary ''' ct = current_process() if not hasattr(ct, '_pulsar_local'): ct._pulsar_local = {} loc = c...
Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value.
def thread_data(name, value=NOTHING, ct=None): '''Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value. ''' ct = ct or current_thread() if is_mainthread(ct): ...
Parse an internet address ``netloc`` and return a tuple with ``host`` and ``port``.
def parse_address(netloc, default_port=8000): '''Parse an internet address ``netloc`` and return a tuple with ``host`` and ``port``.''' if isinstance(netloc, tuple): if len(netloc) != 2: raise ValueError('Invalid address %s' % str(netloc)) return netloc # netloc = native_str(...
Converts the ``connection_string`` into a three elements tuple ``(scheme, host, params)`` where ``scheme`` is a string, ``host`` could be a string or a two elements tuple (for a tcp address) and ``params`` a dictionary of parameters. The ``default_port`` parameter can be used to set the port if a port i...
def parse_connection_string(connection_string, default_port=8000): """Converts the ``connection_string`` into a three elements tuple ``(scheme, host, params)`` where ``scheme`` is a string, ``host`` could be a string or a two elements tuple (for a tcp address) and ``params`` a dictionary of parameters. ...
Check if socket ``sock`` is closed.
def is_socket_closed(sock): # pragma nocover """Check if socket ``sock`` is closed.""" if not sock: return True try: if not poll: # pragma nocover if not select: return False try: return bool(select([sock], [], [], 0.0)[0]) ...
Shutdown and close the socket.
def close_socket(sock): '''Shutdown and close the socket.''' if sock: try: sock.shutdown(socket.SHUT_RDWR) except Exception: pass try: sock.close() except Exception: pass
Return a dictionary of information regarding the server and workers. It invokes the :meth:`extra_server_info` for adding custom information.
async def rpc_server_info(self, request): '''Return a dictionary of information regarding the server and workers. It invokes the :meth:`extra_server_info` for adding custom information. ''' info = await send('arbiter', 'info') info = self.extra_server_info(request, info)...
Bind a ``callback`` to this event.
def bind(self, callback): """Bind a ``callback`` to this event. """ handlers = self._handlers if self._self is None: raise RuntimeError('%s already fired, cannot add callbacks' % self) if handlers is None: handlers = [] self._handlers = handler...
Remove a callback from the list
def unbind(self, callback): """Remove a callback from the list """ handlers = self._handlers if handlers: filtered_callbacks = [f for f in handlers if f != callback] removed_count = len(handlers) - len(filtered_callbacks) if removed_count: ...
Fire the event :param exc: fire the event with an exception :param data: fire an event with data
def fire(self, exc=None, data=None): """Fire the event :param exc: fire the event with an exception :param data: fire an event with data """ o = self._self if o is not None: handlers = self._handlers if self._onetime: self._handle...
Return a :class:`~asyncio.Future` called back once the event has been fired. If the event has been fired already return a resolved future. This method is available only for one-time events
def waiter(self): """Return a :class:`~asyncio.Future` called back once the event has been fired. If the event has been fired already return a resolved future. This method is available only for one-time events """ assert self._onetime, 'One time events only can invoke wa...
Returns the :class:`Event` at ``name``. If no event is registered for ``name`` creates a new :class:`Event` object and returns it.
def event(self, name): """Returns the :class:`Event` at ``name``. If no event is registered for ``name`` creates a new :class:`Event` object and returns it. """ events = self.events() if name not in events: events[name] = Event(name, self, 0) return e...
Fire event at ``name`` if it is registered
def fire_event(self, name, exc=None, data=None): """Fire event at ``name`` if it is registered """ if self._events and name in self._events: self._events[name].fire(exc=exc, data=data)
Register all known events found in ``events`` key-valued parameters.
def bind_events(self, events): '''Register all known events found in ``events`` key-valued parameters. ''' evs = self._events if evs and events: for event in evs.values(): if event.name in events: event.bind(events[event.name])
Copy :ref:`many times events <many-times-event>` from ``other``. All many times events of ``other`` are copied to this handler provided the events handlers already exist.
def copy_many_times_events(self, other): '''Copy :ref:`many times events <many-times-event>` from ``other``. All many times events of ``other`` are copied to this handler provided the events handlers already exist. ''' events = self.events() other_events = other.events(...
Equivalent to ``func(*args, **kwargs)``. This method create a new task for function ``func`` and adds it to the queue. Return a :class:`~asyncio.Future` called back once the task has finished.
def submit(self, func, *args, **kwargs): """Equivalent to ``func(*args, **kwargs)``. This method create a new task for function ``func`` and adds it to the queue. Return a :class:`~asyncio.Future` called back once the task has finished. """ with self._shutdown_lo...
Create a new :class:`FrameParser` instance. :param version: protocol version, the default is 13 :param kind: the kind of parser, and integer between 0 and 3 (check the :class:`FrameParser` documentation for details) :param extensions: not used at the moment :param protocols: not used at the mom...
def frame_parser(version=None, kind=0, extensions=None, protocols=None): '''Create a new :class:`FrameParser` instance. :param version: protocol version, the default is 13 :param kind: the kind of parser, and integer between 0 and 3 (check the :class:`FrameParser` documentation for details) :pa...
Parse the body of a close :class:`Frame`. Returns a tuple (``code``, ``reason``) if successful otherwise raise :class:`.ProtocolError`.
def parse_close(data): '''Parse the body of a close :class:`Frame`. Returns a tuple (``code``, ``reason``) if successful otherwise raise :class:`.ProtocolError`. ''' length = len(data) if length == 0: return 1005, '' elif length == 1: raise ProtocolError("Close frame too sho...
Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading.
def _get_args_for_reloading(): """Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading. """ rv = [sys.executable] py_script = sys.argv[0] if os.name == 'nt' and not os.path.ex...
Spawn a new Python interpreter with the same arguments as this one
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one """ while True: LOGGER.info('Restarting with %s reloader' % self.name) args = _get_args_for_reloading() new_environ = os.environ.copy() new_envir...
Invoke the stop on the event loop method.
def kill(self, sig): '''Invoke the stop on the event loop method.''' if self.is_alive() and self._loop: self._loop.call_soon_threadsafe(self._loop.stop)
Called by the client to encode Authentication header.
def encode(self, method, uri): '''Called by the client to encode Authentication header.''' if not self.username or not self.password: return o = self.options qop = o.get('qop') realm = o.get('realm') nonce = o.get('nonce') entdig = None p_parse...
Takes the given response and tries digest-auth, if needed.
def handle_401(self, response, exc=None): """Takes the given response and tries digest-auth, if needed.""" if response.status_code == 401: s_auth = response.headers.get('www-authenticate', '') if 'digest' not in s_auth.lower(): return request = respons...
The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse`
def handle_wsgi_error(environ, exc): '''The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse` ''' if isinstance(exc, tuple): exc_info = exc exc = exc[1] else: exc_info...
Default renderer for errors.
def render_error(request, exc): '''Default renderer for errors.''' cfg = request.get('pulsar.cfg') debug = cfg.debug if cfg else False response = request.response if not response.content_type: content_type = request.get('default.content_type') response.content_type = request.content_...
Render the ``exception`` traceback
def render_error_debug(request, exception, is_html): '''Render the ``exception`` traceback ''' error = Html('div', cn='well well-lg') if is_html else [] for trace in format_traceback(exception): counter = 0 for line in trace.split('\n'): if line.startswith(' '): ...