text
stringlengths
81
112k
:return: the :class:`Document` node that contains this node, or ``self`` if this node is the document. def document(self): """ :return: the :class:`Document` node that contains this node, or ``self`` if this node is the document. """ if self.is_document: return self return self.adapter.wrap_document(self.adapter.impl_document)
:return: the root :class:`Element` node of the document that contains this node, or ``self`` if this node is the root element. def root(self): """ :return: the root :class:`Element` node of the document that contains this node, or ``self`` if this node is the root element. """ if self.is_root: return self return self.adapter.wrap_node( self.adapter.impl_root_element, self.adapter.impl_document, self.adapter)
Convert a list of underlying implementation nodes into a list of *xml4h* wrapper nodes. def _convert_nodelist(self, impl_nodelist): """ Convert a list of underlying implementation nodes into a list of *xml4h* wrapper nodes. """ nodelist = [ self.adapter.wrap_node(n, self.adapter.impl_document, self.adapter) for n in impl_nodelist] return NodeList(nodelist)
:return: the parent of this node, or *None* of the node has no parent. def parent(self): """ :return: the parent of this node, or *None* of the node has no parent. """ parent_impl_node = self.adapter.get_node_parent(self.impl_node) return self.adapter.wrap_node( parent_impl_node, self.adapter.impl_document, self.adapter)
:return: a :class:`NodeList` of this node's child nodes. def children(self): """ :return: a :class:`NodeList` of this node's child nodes. """ impl_nodelist = self.adapter.get_node_children(self.impl_node) return self._convert_nodelist(impl_nodelist)
:return: the first child node matching the given constraints, or \ *None* if there are no matching child nodes. Delegates to :meth:`NodeList.filter`. def child(self, local_name=None, name=None, ns_uri=None, node_type=None, filter_fn=None): """ :return: the first child node matching the given constraints, or \ *None* if there are no matching child nodes. Delegates to :meth:`NodeList.filter`. """ return self.children(name=name, local_name=local_name, ns_uri=ns_uri, node_type=node_type, filter_fn=filter_fn, first_only=True)
:return: a list of this node's sibling nodes. :rtype: NodeList def siblings(self): """ :return: a list of this node's sibling nodes. :rtype: NodeList """ impl_nodelist = self.adapter.get_node_children(self.parent.impl_node) return self._convert_nodelist( [n for n in impl_nodelist if n != self.impl_node])
:return: a list of this node's siblings that occur *before* this node in the DOM. def siblings_before(self): """ :return: a list of this node's siblings that occur *before* this node in the DOM. """ impl_nodelist = self.adapter.get_node_children(self.parent.impl_node) before_nodelist = [] for n in impl_nodelist: if n == self.impl_node: break before_nodelist.append(n) return self._convert_nodelist(before_nodelist)
:return: a list of this node's siblings that occur *after* this node in the DOM. def siblings_after(self): """ :return: a list of this node's siblings that occur *after* this node in the DOM. """ impl_nodelist = self.adapter.get_node_children(self.parent.impl_node) after_nodelist = [] is_after_myself = False for n in impl_nodelist: if is_after_myself: after_nodelist.append(n) elif n == self.impl_node: is_after_myself = True return self._convert_nodelist(after_nodelist)
Delete this node from the owning document. :param bool destroy: if True the child node will be destroyed in addition to being removed from the document. :returns: the removed child node, or *None* if the child was destroyed. def delete(self, destroy=True): """ Delete this node from the owning document. :param bool destroy: if True the child node will be destroyed in addition to being removed from the document. :returns: the removed child node, or *None* if the child was destroyed. """ removed_child = self.adapter.remove_node_child( self.adapter.get_node_parent(self.impl_node), self.impl_node, destroy_node=destroy) if removed_child is not None: return self.adapter.wrap_node(removed_child, None, self.adapter) else: return None
Clone a node from another document to become a child of this node, by copying the node's data into this document but leaving the node untouched in the source document. The node to be cloned can be a :class:`Node` based on the same underlying XML library implementation and adapter, or a "raw" node from that implementation. :param node: the node in another document to clone. :type node: xml4h or implementation node def clone_node(self, node): """ Clone a node from another document to become a child of this node, by copying the node's data into this document but leaving the node untouched in the source document. The node to be cloned can be a :class:`Node` based on the same underlying XML library implementation and adapter, or a "raw" node from that implementation. :param node: the node in another document to clone. :type node: xml4h or implementation node """ if isinstance(node, xml4h.nodes.Node): child_impl_node = node.impl_node else: child_impl_node = node # Assume it's a valid impl node self.adapter.import_node(self.impl_node, child_impl_node, clone=True)
Transplant a node from another document to become a child of this node, removing it from the source document. The node to be transplanted can be a :class:`Node` based on the same underlying XML library implementation and adapter, or a "raw" node from that implementation. :param node: the node in another document to transplant. :type node: xml4h or implementation node def transplant_node(self, node): """ Transplant a node from another document to become a child of this node, removing it from the source document. The node to be transplanted can be a :class:`Node` based on the same underlying XML library implementation and adapter, or a "raw" node from that implementation. :param node: the node in another document to transplant. :type node: xml4h or implementation node """ if isinstance(node, xml4h.nodes.Node): child_impl_node = node.impl_node original_parent_impl_node = node.parent.impl_node else: child_impl_node = node # Assume it's a valid impl node original_parent_impl_node = self.adapter.get_node_parent(node) self.adapter.import_node(self.impl_node, child_impl_node, original_parent_impl_node, clone=False)
Find :class:`Element` node descendants of this node, with optional constraints to limit the results. :param name: limit results to elements with this name. If *None* or ``'*'`` all element names are matched. :type name: string or None :param ns_uri: limit results to elements within this namespace URI. If *None* all elements are matched, regardless of namespace. :type ns_uri: string or None :param bool first_only: if *True* only return the first result node or *None* if there is no matching node. :returns: a list of :class:`Element` nodes matching any given constraints, or a single node if ``first_only=True``. def find(self, name=None, ns_uri=None, first_only=False): """ Find :class:`Element` node descendants of this node, with optional constraints to limit the results. :param name: limit results to elements with this name. If *None* or ``'*'`` all element names are matched. :type name: string or None :param ns_uri: limit results to elements within this namespace URI. If *None* all elements are matched, regardless of namespace. :type ns_uri: string or None :param bool first_only: if *True* only return the first result node or *None* if there is no matching node. :returns: a list of :class:`Element` nodes matching any given constraints, or a single node if ``first_only=True``. """ if name is None: name = '*' # Match all element names if ns_uri is None: ns_uri = '*' # Match all namespaces impl_nodelist = self.adapter.find_node_elements( self.impl_node, name=name, ns_uri=ns_uri) if first_only: if impl_nodelist: return self.adapter.wrap_node( impl_nodelist[0], self.adapter.impl_document, self.adapter) else: return None return self._convert_nodelist(impl_nodelist)
Find the first :class:`Element` node descendant of this node that matches any optional constraints, or None if there are no matching elements. Delegates to :meth:`find` with ``first_only=True``. def find_first(self, name=None, ns_uri=None): """ Find the first :class:`Element` node descendant of this node that matches any optional constraints, or None if there are no matching elements. Delegates to :meth:`find` with ``first_only=True``. """ return self.find(name=name, ns_uri=ns_uri, first_only=True)
Find :class:`Element` node descendants of the document containing this node, with optional constraints to limit the results. Delegates to :meth:`find` applied to this node's owning document. def find_doc(self, name=None, ns_uri=None, first_only=False): """ Find :class:`Element` node descendants of the document containing this node, with optional constraints to limit the results. Delegates to :meth:`find` applied to this node's owning document. """ return self.document.find(name=name, ns_uri=ns_uri, first_only=first_only)
Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. Delegates to :func:`xml4h.writer.write_node` applied to this node. def write(self, writer=None, encoding='utf-8', indent=0, newline='', omit_declaration=False, node_depth=0, quote_char='"'): """ Serialize this node and its descendants to text, writing the output to a given *writer* or to stdout. :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. Delegates to :func:`xml4h.writer.write_node` applied to this node. """ xml4h.write_node(self, writer=writer, encoding=encoding, indent=indent, newline=newline, omit_declaration=omit_declaration, node_depth=node_depth, quote_char=quote_char)
:return: this node as XML text. Delegates to :meth:`write` def xml(self, indent=4, **kwargs): """ :return: this node as XML text. Delegates to :meth:`write` """ writer = StringIO() self.write(writer, indent=indent, **kwargs) return writer.getvalue()
Perform an XPath query on the current node. :param string xpath: XPath query. :param dict kwargs: Optional keyword arguments that are passed through to the underlying XML library implementation. :return: results of the query as a list of :class:`Node` objects, or a list of base type objects if the XPath query does not reference node objects. def xpath(self, xpath, **kwargs): """ Perform an XPath query on the current node. :param string xpath: XPath query. :param dict kwargs: Optional keyword arguments that are passed through to the underlying XML library implementation. :return: results of the query as a list of :class:`Node` objects, or a list of base type objects if the XPath query does not reference node objects. """ result = self.adapter.xpath_on_node(self.impl_node, xpath, **kwargs) if isinstance(result, (list, tuple)): return [self._maybe_wrap_node(r) for r in result] else: return self._maybe_wrap_node(result)
Add or update this element's attributes, where attributes can be specified in a number of ways. :param attr_obj: a dictionary or list of attribute name/value pairs. :type attr_obj: dict, list, tuple, or None :param ns_uri: a URI defining a namespace for the new attributes. :type ns_uri: string or None :param dict attr_dict: attribute name and values specified as keyword arguments. def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict): """ Add or update this element's attributes, where attributes can be specified in a number of ways. :param attr_obj: a dictionary or list of attribute name/value pairs. :type attr_obj: dict, list, tuple, or None :param ns_uri: a URI defining a namespace for the new attributes. :type ns_uri: string or None :param dict attr_dict: attribute name and values specified as keyword arguments. """ self._set_element_attributes(self.impl_node, attr_obj=attr_obj, ns_uri=ns_uri, **attr_dict)
Get or set this element's attributes as name/value pairs. .. note:: Setting element attributes via this accessor will **remove** any existing attributes, as opposed to the :meth:`set_attributes` method which only updates and replaces them. def attributes(self): """ Get or set this element's attributes as name/value pairs. .. note:: Setting element attributes via this accessor will **remove** any existing attributes, as opposed to the :meth:`set_attributes` method which only updates and replaces them. """ attr_impl_nodes = self.adapter.get_node_attributes(self.impl_node) return AttributeDict(attr_impl_nodes, self.impl_node, self.adapter)
:return: a list of this element's attributes as :class:`Attribute` nodes. def attribute_nodes(self): """ :return: a list of this element's attributes as :class:`Attribute` nodes. """ impl_attr_nodes = self.adapter.get_node_attributes(self.impl_node) wrapped_attr_nodes = [ self.adapter.wrap_node(a, self.adapter.impl_document, self.adapter) for a in impl_attr_nodes] return sorted(wrapped_attr_nodes, key=lambda x: x.name)
:param string name: the name of the attribute to return. :param ns_uri: a URI defining a namespace constraint on the attribute. :type ns_uri: string or None :return: this element's attributes that match ``ns_uri`` as :class:`Attribute` nodes. def attribute_node(self, name, ns_uri=None): """ :param string name: the name of the attribute to return. :param ns_uri: a URI defining a namespace constraint on the attribute. :type ns_uri: string or None :return: this element's attributes that match ``ns_uri`` as :class:`Attribute` nodes. """ attr_impl_node = self.adapter.get_node_attribute_node( self.impl_node, name, ns_uri) return self.adapter.wrap_node( attr_impl_node, self.adapter.impl_document, self.adapter)
Define a namespace prefix that will serve as shorthand for the given namespace URI in element names. :param string prefix: prefix that will serve as an alias for a the namespace URI. :param string ns_uri: namespace URI that will be denoted by the prefix. def set_ns_prefix(self, prefix, ns_uri): """ Define a namespace prefix that will serve as shorthand for the given namespace URI in element names. :param string prefix: prefix that will serve as an alias for a the namespace URI. :param string ns_uri: namespace URI that will be denoted by the prefix. """ self._add_ns_prefix_attr(self.impl_node, prefix, ns_uri)
Add a new child element to this element, with an optional namespace definition. If no namespace is provided the child will be assigned to the default namespace. :param string name: a name for the child node. The name may be used to apply a namespace to the child by including: - a prefix component in the name of the form ``ns_prefix:element_name``, where the prefix has already been defined for a namespace URI (such as via :meth:`set_ns_prefix`). - a literal namespace URI value delimited by curly braces, of the form ``{ns_uri}element_name``. :param ns_uri: a URI specifying the new element's namespace. If the ``name`` parameter specifies a namespace this parameter is ignored. :type ns_uri: string or None :param attributes: collection of attributes to assign to the new child. :type attributes: dict, list, tuple, or None :param text: text value to assign to the new child. :type text: string or None :param bool before_this_element: if *True* the new element is added as a sibling preceding this element, instead of as a child. In other words, the new element will be a child of this element's parent node, and will immediately precent this element in the DOM. :return: the new child as a an :class:`Element` node. def add_element(self, name, ns_uri=None, attributes=None, text=None, before_this_element=False): """ Add a new child element to this element, with an optional namespace definition. If no namespace is provided the child will be assigned to the default namespace. :param string name: a name for the child node. The name may be used to apply a namespace to the child by including: - a prefix component in the name of the form ``ns_prefix:element_name``, where the prefix has already been defined for a namespace URI (such as via :meth:`set_ns_prefix`). - a literal namespace URI value delimited by curly braces, of the form ``{ns_uri}element_name``. :param ns_uri: a URI specifying the new element's namespace. If the ``name`` parameter specifies a namespace this parameter is ignored. :type ns_uri: string or None :param attributes: collection of attributes to assign to the new child. :type attributes: dict, list, tuple, or None :param text: text value to assign to the new child. :type text: string or None :param bool before_this_element: if *True* the new element is added as a sibling preceding this element, instead of as a child. In other words, the new element will be a child of this element's parent node, and will immediately precent this element in the DOM. :return: the new child as a an :class:`Element` node. """ # Determine local name, namespace and prefix info from tag name prefix, local_name, node_ns_uri = \ self.adapter.get_ns_info_from_node_name(name, self.impl_node) if prefix: qname = u'%s:%s' % (prefix, local_name) else: qname = local_name # If no name-derived namespace, apply an alternate namespace if node_ns_uri is None: if ns_uri is None: # Default document namespace node_ns_uri = self.adapter.get_ns_uri_for_prefix( self.impl_node, None) else: # keyword-parameter namespace node_ns_uri = ns_uri # Create element child_elem = self.adapter.new_impl_element( qname, node_ns_uri, parent=self.impl_node) # If element's default namespace was defined by literal uri prefix, # create corresponding xmlns attribute for element... if not prefix and '}' in name: self._set_element_attributes(child_elem, {'xmlns': node_ns_uri}, ns_uri=self.XMLNS_URI) # ...otherwise define keyword-defined namespace as the default, if any elif ns_uri is not None: self._set_element_attributes(child_elem, {'xmlns': ns_uri}, ns_uri=self.XMLNS_URI) # Create subordinate nodes if attributes is not None: self._set_element_attributes(child_elem, attr_obj=attributes) if text is not None: self._add_text(child_elem, text) # Add new element to its parent before a given node... if before_this_element: self.adapter.add_node_child( self.adapter.get_node_parent(self.impl_node), child_elem, before_sibling=self.impl_node) # ...or in the default position, appended after existing nodes else: self.adapter.add_node_child(self.impl_node, child_elem) return self.adapter.wrap_node( child_elem, self.adapter.impl_document, self.adapter)
Add a text node to this element. Adding text with this method is subtly different from assigning a new text value with :meth:`text` accessor, because it "appends" to rather than replacing this element's set of text nodes. :param text: text content to add to this element. :param type: string or anything that can be coerced by :func:`unicode`. def add_text(self, text): """ Add a text node to this element. Adding text with this method is subtly different from assigning a new text value with :meth:`text` accessor, because it "appends" to rather than replacing this element's set of text nodes. :param text: text content to add to this element. :param type: string or anything that can be coerced by :func:`unicode`. """ if not isinstance(text, basestring): text = unicode(text) self._add_text(self.impl_node, text)
Add an instruction node to this element. :param string text: text content to add as an instruction. def add_instruction(self, target, data): """ Add an instruction node to this element. :param string text: text content to add as an instruction. """ self._add_instruction(self.impl_node, target, data)
:return: a list of name/value attribute pairs sorted by attribute name. def items(self): """ :return: a list of name/value attribute pairs sorted by attribute name. """ sorted_keys = sorted(self.keys()) return [(k, self[k]) for k in sorted_keys]
:param string name: the name of an attribute to look up. :return: the namespace URI associated with the named attribute, or None. def namespace_uri(self, name): """ :param string name: the name of an attribute to look up. :return: the namespace URI associated with the named attribute, or None. """ a_node = self.adapter.get_node_attribute_node(self.impl_element, name) if a_node is None: return None return self.adapter.get_node_namespace_uri(a_node)
:param string name: the name of an attribute to look up. :return: the prefix component of the named attribute's name, or None. def prefix(self, name): """ :param string name: the name of an attribute to look up. :return: the prefix component of the named attribute's name, or None. """ a_node = self.adapter.get_node_attribute_node(self.impl_element, name) if a_node is None: return None return a_node.prefix
:return: the :class:`Element` that contains these attributes. def element(self): """ :return: the :class:`Element` that contains these attributes. """ return self.adapter.wrap_node( self.impl_element, self.adapter.impl_document, self.adapter)
Apply filters to the set of nodes in this list. :param local_name: a local name used to filter the nodes. :type local_name: string or None :param name: a name used to filter the nodes. :type name: string or None :param ns_uri: a namespace URI used to filter the nodes. If *None* all nodes are returned regardless of namespace. :type ns_uri: string or None :param node_type: a node type definition used to filter the nodes. :type node_type: int node type constant, class, or None :param filter_fn: an arbitrary function to filter nodes in this list. This function must accept a single :class:`Node` argument and return a bool indicating whether to include the node in the filtered results. .. note:: if ``filter_fn`` is provided all other filter arguments are ignore. :type filter_fn: function or None :return: the type of the return value depends on the value of the ``first_only`` parameter and how many nodes match the filter: - if ``first_only=False`` return a :class:`NodeList` of filtered nodes, which will be empty if there are no matching nodes. - if ``first_only=True`` and at least one node matches, return the first matching :class:`Node` - if ``first_only=True`` and there are no matching nodes, return *None* def filter(self, local_name=None, name=None, ns_uri=None, node_type=None, filter_fn=None, first_only=False): """ Apply filters to the set of nodes in this list. :param local_name: a local name used to filter the nodes. :type local_name: string or None :param name: a name used to filter the nodes. :type name: string or None :param ns_uri: a namespace URI used to filter the nodes. If *None* all nodes are returned regardless of namespace. :type ns_uri: string or None :param node_type: a node type definition used to filter the nodes. :type node_type: int node type constant, class, or None :param filter_fn: an arbitrary function to filter nodes in this list. This function must accept a single :class:`Node` argument and return a bool indicating whether to include the node in the filtered results. .. note:: if ``filter_fn`` is provided all other filter arguments are ignore. :type filter_fn: function or None :return: the type of the return value depends on the value of the ``first_only`` parameter and how many nodes match the filter: - if ``first_only=False`` return a :class:`NodeList` of filtered nodes, which will be empty if there are no matching nodes. - if ``first_only=True`` and at least one node matches, return the first matching :class:`Node` - if ``first_only=True`` and there are no matching nodes, return *None* """ # Build our own filter function unless a custom function is provided if filter_fn is None: def filter_fn(n): # Test node type first in case other tests require this type if node_type is not None: # Node type can be specified as an integer constant (e.g. # ELEMENT_NODE) or a class. if isinstance(node_type, int): if not n.is_type(node_type): return False elif n.__class__ != node_type: return False if name is not None and n.name != name: return False if local_name is not None and n.local_name != local_name: return False if ns_uri is not None and n.ns_uri != ns_uri: return False return True # Filter nodes nodelist = filter(filter_fn, self) # If requested, return just the first node (or None if no nodes) if first_only: return nodelist[0] if nodelist else None else: return NodeList(nodelist)
Get all analytics of a job. def get_all_analytics(user, job_id): """Get all analytics of a job.""" args = schemas.args(flask.request.args.to_dict()) v1_utils.verify_existence_and_get(job_id, models.JOBS) query = v1_utils.QueryBuilder(_TABLE, args, _A_COLUMNS) # If not admin nor rh employee then restrict the view to the team if user.is_not_super_admin() and not user.is_read_only_user(): query.add_extra_condition(_TABLE.c.team_id.in_(user.teams_ids)) query.add_extra_condition(_TABLE.c.job_id == job_id) nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name) return flask.jsonify({'analytics': rows, '_meta': {'count': nb_rows}})
Get an analytic. def get_analytic(user, job_id, anc_id): """Get an analytic.""" v1_utils.verify_existence_and_get(job_id, models.JOBS) analytic = v1_utils.verify_existence_and_get(anc_id, _TABLE) analytic = dict(analytic) if not user.is_in_team(analytic['team_id']): raise dci_exc.Unauthorized() return flask.jsonify({'analytic': analytic})
Serialize an *xml4h* DOM node and its descendants to text, writing the output to a given *writer* or to stdout. :param node: the DOM node whose content and descendants will be serialized. :type node: an :class:`xml4h.nodes.Node` or subclass :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent. :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. def write_node(node, writer=None, encoding='utf-8', indent=0, newline='', omit_declaration=False, node_depth=0, quote_char='"'): """ Serialize an *xml4h* DOM node and its descendants to text, writing the output to a given *writer* or to stdout. :param node: the DOM node whose content and descendants will be serialized. :type node: an :class:`xml4h.nodes.Node` or subclass :param writer: an object such as a file or stream to which XML text is sent. If *None* text is sent to :attr:`sys.stdout`. :type writer: a file, stream, etc or None :param string encoding: the character encoding for serialized text. :param indent: indentation prefix to apply to descendent nodes for pretty-printing. The value can take many forms: - *int*: the number of spaces to indent. 0 means no indent. - *string*: a literal prefix for indented nodes, such as ``\\t``. - *bool*: no indent if *False*, four spaces indent if *True*. - *None*: no indent. :type indent: string, int, bool, or None :param newline: the string value used to separate lines of output. The value can take a number of forms: - *string*: the literal newline value, such as ``\\n`` or ``\\r``. An empty string means no newline. - *bool*: no newline if *False*, ``\\n`` newline if *True*. - *None*: no newline. :type newline: string, bool, or None :param boolean omit_declaration: if *True* the XML declaration header is omitted, otherwise it is included. Note that the declaration is only output when serializing an :class:`xml4h.nodes.Document` node. :param int node_depth: the indentation level to start at, such as 2 to indent output as if the given *node* has two ancestors. This parameter will only be useful if you need to output XML text fragments that can be assembled into a document. This parameter has no effect unless indentation is applied. :param string quote_char: the character that delimits quoted content. You should never need to mess with this. """ def _sanitize_write_value(value): """Return XML-encoded value.""" if not value: return value return (value .replace("&", "&amp;") .replace("<", "&lt;") .replace("\"", "&quot;") .replace(">", "&gt;") ) def _write_node_impl(node, node_depth): """ Internal write implementation that does the real work while keeping track of node depth. """ # Output document declaration if we're outputting the whole doc if node.is_document: if not omit_declaration: writer.write( '<?xml version=%s1.0%s' % (quote_char, quote_char)) if encoding: writer.write(' encoding=%s%s%s' % (quote_char, encoding, quote_char)) writer.write('?>%s' % newline) for child in node.children: _write_node_impl(child, node_depth) # node_depth not incremented writer.write(newline) elif node.is_document_type: writer.write("<!DOCTYPE %s SYSTEM %s%s%s" % (node.name, quote_char, node.public_id)) if node.system_id is not None: writer.write( " %s%s%s" % (quote_char, node.system_id, quote_char)) if node.children: writer.write("[") for child in node.children: _write_node_impl(child, node_depth + 1) writer.write("]") writer.write(">") elif node.is_text: writer.write(_sanitize_write_value(node.value)) elif node.is_cdata: if ']]>' in node.value: raise ValueError("']]>' is not allowed in CDATA node value") writer.write("<![CDATA[%s]]>" % node.value) #elif node.is_entity_reference: # TODO elif node.is_entity: writer.write(newline + indent * node_depth) writer.write("<!ENTITY ") if node.is_paremeter_entity: writer.write('%% ') writer.write("%s %s%s%s>" % (node.name, quote_char, node.value, quote_char)) elif node.is_processing_instruction: writer.write(newline + indent * node_depth) writer.write("<?%s %s?>" % (node.target, node.data)) elif node.is_comment: if '--' in node.value: raise ValueError("'--' is not allowed in COMMENT node value") writer.write("<!--%s-->" % node.value) elif node.is_notation: writer.write(newline + indent * node_depth) writer.write("<!NOTATION %s" % node.name) if node.is_system_identifier: writer.write(" system %s%s%s>" % (quote_char, node.external_id, quote_char)) elif node.is_system_identifier: writer.write(" system %s%s%s %s%s%s>" % (quote_char, node.external_id, quote_char, quote_char, node.uri, quote_char)) elif node.is_attribute: writer.write(" %s=%s" % (node.name, quote_char)) writer.write(_sanitize_write_value(node.value)) writer.write(quote_char) elif node.is_element: # Only need a preceding newline if we're in a sub-element if node_depth > 0: writer.write(newline) writer.write(indent * node_depth) writer.write("<" + node.name) for attr in node.attribute_nodes: _write_node_impl(attr, node_depth) if node.children: found_indented_child = False writer.write(">") for child in node.children: _write_node_impl(child, node_depth + 1) if not (child.is_text or child.is_comment or child.is_cdata): found_indented_child = True if found_indented_child: writer.write(newline + indent * node_depth) writer.write('</%s>' % node.name) else: writer.write('/>') else: raise exceptions.Xml4hImplementationBug( 'Cannot write node with class: %s' % node.__class__) # Sanitize whitespace parameters if indent is True: indent = ' ' * 4 elif indent is False: indent = '' elif isinstance(indent, int): indent = ' ' * indent # If indent but no newline set, always apply a newline (it makes sense) if indent and not newline: newline = True if newline is None or newline is False: newline = '' elif newline is True: newline = '\n' # We always need a writer, use stdout by default if writer is None: writer = sys.stdout # Apply a text encoding if we have one if encoding is None: writer = writer else: writer = codecs.getwriter(encoding)(writer) # Do the business... _write_node_impl(node, node_depth)
When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False, the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk. :param chunk: a chunk in bytes to encrypt or decrypt. :param key: a 32 bytes key in bytes. :param algo: a string of algorithm. Can be "srp" , "AES" or "twf" :param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted. :param assoc_data: bytes string of additional data for GCM Authentication. :return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk. def encry_decry_chunk(chunk, key, algo, bool_encry, assoc_data): """ When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False, the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk. :param chunk: a chunk in bytes to encrypt or decrypt. :param key: a 32 bytes key in bytes. :param algo: a string of algorithm. Can be "srp" , "AES" or "twf" :param bool_encry: if bool_encry is True, chunk is encrypted. Else, it will be decrypted. :param assoc_data: bytes string of additional data for GCM Authentication. :return: if bool_encry is True, corresponding nonce + cipherchunk else, a decrypted chunk. """ engine = botan.cipher(algo=algo, encrypt=bool_encry) engine.set_key(key=key) engine.set_assoc_data(assoc_data) if bool_encry is True: nonce = generate_nonce_timestamp() engine.start(nonce=nonce) return nonce + engine.finish(chunk) else: nonce = chunk[:__nonce_length__] encryptedchunk = chunk[__nonce_length__:__nonce_length__ + __gcmtag_length__ + __chunk_size__] engine.start(nonce=nonce) decryptedchunk = engine.finish(encryptedchunk) if decryptedchunk == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") return decryptedchunk
Query Bugzilla API to retrieve the needed infos. def retrieve_info(self): """Query Bugzilla API to retrieve the needed infos.""" scheme = urlparse(self.url).scheme netloc = urlparse(self.url).netloc query = urlparse(self.url).query if scheme not in ('http', 'https'): return for item in query.split('&'): if 'id=' in item: ticket_id = item.split('=')[1] break else: return bugzilla_url = '%s://%s/%s%s' % (scheme, netloc, _URI_BASE, ticket_id) result = requests.get(bugzilla_url) self.status_code = result.status_code if result.status_code == 200: tree = ElementTree.fromstring(result.content) self.title = tree.findall("./bug/short_desc").pop().text self.issue_id = tree.findall("./bug/bug_id").pop().text self.reporter = tree.findall("./bug/reporter").pop().text self.assignee = tree.findall("./bug/assigned_to").pop().text self.status = tree.findall("./bug/bug_status").pop().text self.product = tree.findall("./bug/product").pop().text self.component = tree.findall("./bug/component").pop().text self.created_at = tree.findall("./bug/creation_ts").pop().text self.updated_at = tree.findall("./bug/delta_ts").pop().text try: self.closed_at = ( tree.findall("./bug/cf_last_closed").pop().text ) except IndexError: # cf_last_closed is present only if the issue has been closed # if not present it raises an IndexError, meaning the issue # isn't closed yet, which is a valid use case. pass
'Minimum length' validation_function generator. Returns a validation_function to check that len(x) >= min_length (strict=False, default) or len(x) > min_length (strict=True) :param min_length: minimum length for x :param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len(x) > min_length (strict=True) :return: def minlen(min_length, strict=False # type: bool ): """ 'Minimum length' validation_function generator. Returns a validation_function to check that len(x) >= min_length (strict=False, default) or len(x) > min_length (strict=True) :param min_length: minimum length for x :param strict: Boolean flag to switch between len(x) >= min_length (strict=False) and len(x) > min_length (strict=True) :return: """ if strict: def minlen_(x): if len(x) > min_length: return True else: # raise Failure('minlen: len(x) > ' + str(min_length) + ' does not hold for x=' + str(x)) raise TooShort(wrong_value=x, min_length=min_length, strict=True) else: def minlen_(x): if len(x) >= min_length: return True else: # raise Failure('minlen: len(x) >= ' + str(min_length) + ' does not hold for x=' + str(x)) raise TooShort(wrong_value=x, min_length=min_length, strict=False) minlen_.__name__ = 'length_{}greater_than_{}'.format('strictly_' if strict else '', min_length) return minlen_
'Maximum length' validation_function generator. Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True) :param max_length: maximum length for x :param strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length (strict=True) :return: def maxlen(max_length, strict=False # type: bool ): """ 'Maximum length' validation_function generator. Returns a validation_function to check that len(x) <= max_length (strict=False, default) or len(x) < max_length (strict=True) :param max_length: maximum length for x :param strict: Boolean flag to switch between len(x) <= max_length (strict=False) and len(x) < max_length (strict=True) :return: """ if strict: def maxlen_(x): if len(x) < max_length: return True else: # raise Failure('maxlen: len(x) < ' + str(max_length) + ' does not hold for x=' + str(x)) raise TooLong(wrong_value=x, max_length=max_length, strict=True) else: def maxlen_(x): if len(x) <= max_length: return True else: # raise Failure('maxlen: len(x) <= ' + str(max_length) + ' does not hold for x=' + str(x)) raise TooLong(wrong_value=x, max_length=max_length, strict=False) maxlen_.__name__ = 'length_{}lesser_than_{}'.format('strictly_' if strict else '', max_length) return maxlen_
'length equals' validation function generator. Returns a validation_function to check that `len(x) == ref_length` :param ref_length: :return: def has_length(ref_length): """ 'length equals' validation function generator. Returns a validation_function to check that `len(x) == ref_length` :param ref_length: :return: """ def has_length_(x): if len(x) == ref_length: return True else: raise WrongLength(wrong_value=x, ref_length=ref_length) has_length_.__name__ = 'length_equals_{}'.format(ref_length) return has_length_
'Is length between' validation_function generator. Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left` flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce `min_len < len(x) <= max_len`. :param min_len: minimum length for x :param max_len: maximum length for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: def length_between(min_len, max_len, open_left=False, # type: bool open_right=False # type: bool ): """ 'Is length between' validation_function generator. Returns a validation_function to check that `min_len <= len(x) <= max_len (default)`. `open_right` and `open_left` flags allow to transform each side into strict mode. For example setting `open_left=True` will enforce `min_len < len(x) <= max_len`. :param min_len: minimum length for x :param max_len: maximum length for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: """ if open_left and open_right: def length_between_(x): if (min_len < len(x)) and (len(x) < max_len): return True else: # raise Failure('length between: {} < len(x) < {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len, right_strict=True) elif open_left: def length_between_(x): if (min_len < len(x)) and (len(x) <= max_len): return True else: # raise Failure('length between: {} < len(x) <= {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=True, max_length=max_len, right_strict=False) elif open_right: def length_between_(x): if (min_len <= len(x)) and (len(x) < max_len): return True else: # raise Failure('length between: {} <= len(x) < {} does not hold for x={}'.format(min_len, max_len, # x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len, right_strict=True) else: def length_between_(x): if (min_len <= len(x)) and (len(x) <= max_len): return True else: # raise Failure('length between: {} <= len(x) <= {} does not hold for x={}'.format(min_len, # max_len, x)) raise LengthNotInRange(wrong_value=x, min_length=min_len, left_strict=False, max_length=max_len, right_strict=False) length_between_.__name__ = 'length_between_{}_and_{}'.format(min_len, max_len) return length_between_
'Values in' validation_function generator. Returns a validation_function to check that x is in the provided set of allowed values :param allowed_values: a set of allowed values :return: def is_in(allowed_values # type: Set ): """ 'Values in' validation_function generator. Returns a validation_function to check that x is in the provided set of allowed values :param allowed_values: a set of allowed values :return: """ def is_in_allowed_values(x): if x in allowed_values: return True else: # raise Failure('is_in: x in ' + str(allowed_values) + ' does not hold for x=' + str(x)) raise NotInAllowedValues(wrong_value=x, allowed_values=allowed_values) is_in_allowed_values.__name__ = 'is_in_{}'.format(allowed_values) return is_in_allowed_values
'Is subset' validation_function generator. Returns a validation_function to check that x is a subset of reference_set :param reference_set: the reference set :return: def is_subset(reference_set # type: Set ): """ 'Is subset' validation_function generator. Returns a validation_function to check that x is a subset of reference_set :param reference_set: the reference set :return: """ def is_subset_of(x): missing = x - reference_set if len(missing) == 0: return True else: # raise Failure('is_subset: len(x - reference_set) == 0 does not hold for x=' + str(x) # + ' and reference_set=' + str(reference_set) + '. x contains unsupported ' # 'elements ' + str(missing)) raise NotSubset(wrong_value=x, reference_set=reference_set, unsupported=missing) is_subset_of.__name__ = 'is_subset_of_{}'.format(reference_set) return is_subset_of
'Contains' validation_function generator. Returns a validation_function to check that `ref_value in x` :param ref_value: a value that must be present in x :return: def contains(ref_value): """ 'Contains' validation_function generator. Returns a validation_function to check that `ref_value in x` :param ref_value: a value that must be present in x :return: """ def contains_ref_value(x): if ref_value in x: return True else: raise DoesNotContainValue(wrong_value=x, ref_value=ref_value) contains_ref_value.__name__ = 'contains_{}'.format(ref_value) return contains_ref_value
'Is superset' validation_function generator. Returns a validation_function to check that x is a superset of reference_set :param reference_set: the reference set :return: def is_superset(reference_set # type: Set ): """ 'Is superset' validation_function generator. Returns a validation_function to check that x is a superset of reference_set :param reference_set: the reference set :return: """ def is_superset_of(x): missing = reference_set - x if len(missing) == 0: return True else: # raise Failure('is_superset: len(reference_set - x) == 0 does not hold for x=' + str(x) # + ' and reference_set=' + str(reference_set) + '. x does not contain required ' # 'elements ' + str(missing)) raise NotSuperset(wrong_value=x, reference_set=reference_set, missing=missing) is_superset_of.__name__ = 'is_superset_of_{}'.format(reference_set) return is_superset_of
Generates a validation_function for collection inputs where each element of the input will be validated against the validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced with an 'and_'. Note that if you want to apply DIFFERENT validation_functions for each element in the input, you should rather use on_each_. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: def on_all_(*validation_func): """ Generates a validation_function for collection inputs where each element of the input will be validated against the validation_functions provided. For convenience, a list of validation_functions can be provided and will be replaced with an 'and_'. Note that if you want to apply DIFFERENT validation_functions for each element in the input, you should rather use on_each_. :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ # create the validation functions validation_function_func = _process_validation_function_s(list(validation_func)) def on_all_val(x): # validate all elements in x in turn for idx, x_elt in enumerate(x): try: res = validation_function_func(x_elt) except Exception as e: raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=e) if not result_is_success(res): # one element of x was not valid > raise # raise Failure('on_all_(' + str(validation_func) + '): failed validation for input ' # 'element [' + str(idx) + ']: ' + str(x_elt)) raise InvalidItemInSequence(wrong_value=x_elt, wrapped_func=validation_function_func, validation_outcome=res) return True on_all_val.__name__ = 'apply_<{}>_on_all_elts'.format(get_callable_name(validation_function_func)) return on_all_val
Generates a validation_function for collection inputs where each element of the input will be validated against the corresponding validation_function(s) in the validation_functions_collection. Validators inside the tuple can be provided as a list for convenience, this will be replaced with an 'and_' operator if the list has more than one element. Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use on_all_. :param validation_functions_collection: a sequence of (base validation function or list of base validation functions to use). A base validation function may be a callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: def on_each_(*validation_functions_collection): """ Generates a validation_function for collection inputs where each element of the input will be validated against the corresponding validation_function(s) in the validation_functions_collection. Validators inside the tuple can be provided as a list for convenience, this will be replaced with an 'and_' operator if the list has more than one element. Note that if you want to apply the SAME validation_functions to all elements in the input, you should rather use on_all_. :param validation_functions_collection: a sequence of (base validation function or list of base validation functions to use). A base validation function may be a callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :return: """ # create a tuple of validation functions. validation_function_funcs = tuple(_process_validation_function_s(validation_func) for validation_func in validation_functions_collection) # generate a validation function based on the tuple of validation_functions lists def on_each_val(x # type: Tuple ): if len(validation_function_funcs) != len(x): raise Failure('on_each_: x does not have the same number of elements than validation_functions_collection.') else: # apply each validation_function on the input with the same position in the collection idx = -1 for elt, validation_function_func in zip(x, validation_function_funcs): idx += 1 try: res = validation_function_func(elt) except Exception as e: raise InvalidItemInSequence(wrong_value=elt, wrapped_func=validation_function_func, validation_outcome=e) if not result_is_success(res): # one validation_function was unhappy > raise # raise Failure('on_each_(' + str(validation_functions_collection) + '): _validation_function [' + str(idx) # + '] (' + str(validation_functions_collection[idx]) + ') failed validation for ' # 'input ' + str(x[idx])) raise InvalidItemInSequence(wrong_value=elt, wrapped_func=validation_function_func, validation_outcome=res) return True on_each_val.__name__ = 'map_<{}>_on_elts' \ ''.format('(' + ', '.join([get_callable_name(f) for f in validation_function_funcs]) + ')') return on_each_val
Get all the jobs events from a given sequence number. def get_jobs_events_from_sequence(user, sequence): """Get all the jobs events from a given sequence number.""" args = schemas.args(flask.request.args.to_dict()) if user.is_not_super_admin(): raise dci_exc.Unauthorized() query = sql.select([models.JOBS_EVENTS]). \ select_from(models.JOBS_EVENTS.join(models.JOBS, models.JOBS.c.id == models.JOBS_EVENTS.c.job_id)). \ where(_TABLE.c.id >= sequence) sort_list = v1_utils.sort_query(args['sort'], _JOBS_EVENTS_COLUMNS, default='created_at') query = v1_utils.add_sort_to_query(query, sort_list) if args.get('limit', None): query = query.limit(args.get('limit')) if args.get('offset', None): query = query.offset(args.get('offset')) rows = flask.g.db_conn.execute(query).fetchall() query_nb_rows = sql.select([func.count(models.JOBS_EVENTS.c.id)]) nb_rows = flask.g.db_conn.execute(query_nb_rows).scalar() return json.jsonify({'jobs_events': rows, '_meta': {'count': nb_rows}})
Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer. :Parameters: f : `file` A plain text file pointer containing XML to process def from_file(cls, f): """ Constructs a :class:`~mwxml.iteration.dump.Dump` from a `file` pointer. :Parameters: f : `file` A plain text file pointer containing XML to process """ element = ElementIterator.from_file(f) assert element.tag == "mediawiki" return cls.from_element(element)
Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block. :Parameters: page_xml : `str` | `file` Either a plain string or a file containing <page> block XML to process def from_page_xml(cls, page_xml): """ Constructs a :class:`~mwxml.iteration.dump.Dump` from a <page> block. :Parameters: page_xml : `str` | `file` Either a plain string or a file containing <page> block XML to process """ header = """ <mediawiki xmlns="http://www.mediawiki.org/xml/export-0.5/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mediawiki.org/xml/export-0.5/ http://www.mediawiki.org/xml/export-0.5.xsd" version="0.5" xml:lang="en"> <siteinfo> </siteinfo> """ footer = "</mediawiki>" return cls.from_file(mwtypes.files.concat(header, page_xml, footer))
Calculate a 32 bytes key derivation with Argon2. :param passphrase: A string of any length specified by user. :param salt: 512 bits generated by Botan Random Number Generator. :return: a 32 bytes keys. def calc_derivation(passphrase, salt): """ Calculate a 32 bytes key derivation with Argon2. :param passphrase: A string of any length specified by user. :param salt: 512 bits generated by Botan Random Number Generator. :return: a 32 bytes keys. """ argonhash = argon2.low_level.hash_secret_raw((str.encode(passphrase)), salt=salt, hash_len=32, time_cost=__argon2_timing_cost__, memory_cost=__argon2_memory_cost__, parallelism=__argon2_parallelism__, type=argon2.low_level.Type.I) return argonhash
Return contatenated value of all text node children of this element def get_node_text(self, node): """ Return contatenated value of all text node children of this element """ text_children = [n.nodeValue for n in self.get_node_children(node) if n.nodeType == xml.dom.Node.TEXT_NODE] if text_children: return u''.join(text_children) else: return None
Set text value as sole Text child node of element; any existing Text nodes are removed def set_node_text(self, node, text): """ Set text value as sole Text child node of element; any existing Text nodes are removed """ # Remove any existing Text node children for child in self.get_node_children(node): if child.nodeType == xml.dom.Node.TEXT_NODE: self.remove_node_child(node, child, True) if text is not None: text_node = self.new_impl_text(text) self.add_node_child(node, text_node)
Create strings from glob strings. def _get_contents(self): """Create strings from glob strings.""" def files(): for value in super(GlobBundle, self)._get_contents(): for path in glob.glob(value): yield path return list(files())
Test if the given type is a generic type. This includes Generic itself, but excludes special typing constructs such as Union, Tuple, Callable, ClassVar. Examples:: is_generic_type(int) == False is_generic_type(Union[int, str]) == False is_generic_type(Union[int, T]) == False is_generic_type(ClassVar[List[int]]) == False is_generic_type(Callable[..., T]) == False is_generic_type(Generic) == True is_generic_type(Generic[T]) == True is_generic_type(Iterable[int]) == True is_generic_type(Mapping) == True is_generic_type(MutableMapping[T, List[int]]) == True is_generic_type(Sequence[Union[str, bytes]]) == True def is_generic_type(tp): """Test if the given type is a generic type. This includes Generic itself, but excludes special typing constructs such as Union, Tuple, Callable, ClassVar. Examples:: is_generic_type(int) == False is_generic_type(Union[int, str]) == False is_generic_type(Union[int, T]) == False is_generic_type(ClassVar[List[int]]) == False is_generic_type(Callable[..., T]) == False is_generic_type(Generic) == True is_generic_type(Generic[T]) == True is_generic_type(Iterable[int]) == True is_generic_type(Mapping) == True is_generic_type(MutableMapping[T, List[int]]) == True is_generic_type(Sequence[Union[str, bytes]]) == True """ if NEW_TYPING: return (isinstance(tp, type) and issubclass(tp, Generic) or isinstance(tp, _GenericAlias) and tp.__origin__ not in (Union, tuple, ClassVar, collections.abc.Callable)) # SMA: refering to is_callable_type and is_tuple_type to avoid duplicate code return isinstance(tp, GenericMeta) and not is_callable_type(tp) and not is_tuple_type(tp)
Test if the type is a union type. Examples:: is_union_type(int) == False is_union_type(Union) == True is_union_type(Union[int, int]) == False is_union_type(Union[T, int]) == True def is_union_type(tp): """Test if the type is a union type. Examples:: is_union_type(int) == False is_union_type(Union) == True is_union_type(Union[int, int]) == False is_union_type(Union[T, int]) == True """ if NEW_TYPING: return (tp is Union or isinstance(tp, _GenericAlias) and tp.__origin__ is Union) try: from typing import _Union return type(tp) is _Union except ImportError: # SMA: support for very old typing module <=3.5.3 return type(tp) is Union or type(tp) is type(Union)
Test if the type represents a class variable. Examples:: is_classvar(int) == False is_classvar(ClassVar) == True is_classvar(ClassVar[int]) == True is_classvar(ClassVar[List[T]]) == True def is_classvar(tp): """Test if the type represents a class variable. Examples:: is_classvar(int) == False is_classvar(ClassVar) == True is_classvar(ClassVar[int]) == True is_classvar(ClassVar[List[T]]) == True """ if NEW_TYPING: return (tp is ClassVar or isinstance(tp, _GenericAlias) and tp.__origin__ is ClassVar) try: from typing import _ClassVar return type(tp) is _ClassVar except: # SMA: support for very old typing module <=3.5.3 return False
Parse an XML document into an *xml4h*-wrapped DOM representation using an underlying XML library implementation. :param to_parse: an XML document file, document string, or the path to an XML file. If a string value is given that contains a ``<`` character it is treated as literal XML data, otherwise a string value is treated as a file path. :type to_parse: a file-like object or string :param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace nodes are stripped from the parsed document, since these are usually noise introduced by XML docs serialized to be human-friendly. :param adapter: the *xml4h* implementation adapter class used to parse the document and to interact with the resulting nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: an :class:`xml4h.nodes.Document` node representing the parsed document. Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or :meth:`~xml4h.impls.interface.parse_file` implementation. def parse(to_parse, ignore_whitespace_text_nodes=True, adapter=None): """ Parse an XML document into an *xml4h*-wrapped DOM representation using an underlying XML library implementation. :param to_parse: an XML document file, document string, or the path to an XML file. If a string value is given that contains a ``<`` character it is treated as literal XML data, otherwise a string value is treated as a file path. :type to_parse: a file-like object or string :param bool ignore_whitespace_text_nodes: if ``True`` pure whitespace nodes are stripped from the parsed document, since these are usually noise introduced by XML docs serialized to be human-friendly. :param adapter: the *xml4h* implementation adapter class used to parse the document and to interact with the resulting nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: an :class:`xml4h.nodes.Document` node representing the parsed document. Delegates to an adapter's :meth:`~xml4h.impls.interface.parse_string` or :meth:`~xml4h.impls.interface.parse_file` implementation. """ if adapter is None: adapter = best_adapter if isinstance(to_parse, basestring) and '<' in to_parse: return adapter.parse_string(to_parse, ignore_whitespace_text_nodes) else: return adapter.parse_file(to_parse, ignore_whitespace_text_nodes)
Return a :class:`~xml4h.builder.Builder` that represents an element in a new or existing XML DOM and provides "chainable" methods focussed specifically on adding XML content. :param tagname_or_element: a string name for the root node of a new XML document, or an :class:`~xml4h.nodes.Element` node in an existing document. :type tagname_or_element: string or :class:`~xml4h.nodes.Element` node :param ns_uri: a namespace URI to apply to the new root node. This argument has no effect this method is acting on an element. :type ns_uri: string or None :param adapter: the *xml4h* implementation adapter class used to interact with the document DOM nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: a :class:`~xml4h.builder.Builder` instance that represents an :class:`~xml4h.nodes.Element` node in an XML DOM. def build(tagname_or_element, ns_uri=None, adapter=None): """ Return a :class:`~xml4h.builder.Builder` that represents an element in a new or existing XML DOM and provides "chainable" methods focussed specifically on adding XML content. :param tagname_or_element: a string name for the root node of a new XML document, or an :class:`~xml4h.nodes.Element` node in an existing document. :type tagname_or_element: string or :class:`~xml4h.nodes.Element` node :param ns_uri: a namespace URI to apply to the new root node. This argument has no effect this method is acting on an element. :type ns_uri: string or None :param adapter: the *xml4h* implementation adapter class used to interact with the document DOM nodes. If None, :attr:`best_adapter` will be used. :type adapter: adapter class or None :return: a :class:`~xml4h.builder.Builder` instance that represents an :class:`~xml4h.nodes.Element` node in an XML DOM. """ if adapter is None: adapter = best_adapter if isinstance(tagname_or_element, basestring): doc = adapter.create_document( tagname_or_element, ns_uri=ns_uri) element = doc.root elif isinstance(tagname_or_element, xml4h.nodes.Element): element = tagname_or_element else: raise xml4h.exceptions.IncorrectArgumentTypeException( tagname_or_element, [basestring, xml4h.nodes.Element]) return Builder(element)
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return: def get_none_policy_text(none_policy, # type: int verbose=False # type: bool ): """ Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return: """ if none_policy is NonePolicy.SKIP: return "accept None without performing validation" if verbose else 'SKIP' elif none_policy is NonePolicy.FAIL: return "fail on None without performing validation" if verbose else 'FAIL' elif none_policy is NonePolicy.VALIDATE: return "validate None as any other values" if verbose else 'VALIDATE' elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_FAIL: return "accept None without validation if the argument is optional, otherwise fail on None" if verbose \ else 'SKIP_IF_NONABLE_ELSE_FAIL' elif none_policy is NoneArgPolicy.SKIP_IF_NONABLE_ELSE_VALIDATE: return "accept None without validation if the argument is optional, otherwise validate None as any other " \ "values" if verbose else 'SKIP_IF_NONABLE_ELSE_VALIDATE' else: raise ValueError('Invalid none_policy ' + str(none_policy))
Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy :param validation_callable: :param none_policy: an int representing the None policy, see NonePolicy :return: def _add_none_handler(validation_callable, # type: Callable none_policy # type: int ): # type: (...) -> Callable """ Adds a wrapper or nothing around the provided validation_callable, depending on the selected policy :param validation_callable: :param none_policy: an int representing the None policy, see NonePolicy :return: """ if none_policy is NonePolicy.SKIP: return _none_accepter(validation_callable) # accept all None values elif none_policy is NonePolicy.FAIL: return _none_rejecter(validation_callable) # reject all None values elif none_policy is NonePolicy.VALIDATE: return validation_callable # do not handle None specifically, do not wrap else: raise ValueError('Invalid none_policy : ' + str(none_policy))
Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type (second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names (fully qualified for the first type, __name__ for the second) For example ``` > new_type = add_base_type_dynamically(ValidationError, ValueError) > repr(new_type) "<class 'valid8.entry_points.ValidationError+ValueError'>" ``` :return: def add_base_type_dynamically(error_type, additional_type): """ Utility method to create a new type dynamically, inheriting from both error_type (first) and additional_type (second). The class representation (repr(cls)) of the resulting class reflects this by displaying both names (fully qualified for the first type, __name__ for the second) For example ``` > new_type = add_base_type_dynamically(ValidationError, ValueError) > repr(new_type) "<class 'valid8.entry_points.ValidationError+ValueError'>" ``` :return: """ # the new type created dynamically, with the same name class new_error_type(with_metaclass(MetaReprForValidator, error_type, additional_type, object)): pass new_error_type.__name__ = error_type.__name__ + '[' + additional_type.__name__ + ']' if sys.version_info >= (3, 0): new_error_type.__qualname__ = error_type.__qualname__ + '[' + additional_type.__qualname__+ ']' new_error_type.__module__ = error_type.__module__ return new_error_type
Validates value `value` using validation function(s) `base_validator_s`. As opposed to `is_valid`, this function raises a `ValidationError` if validation fails. It is therefore designed to be used for defensive programming, in an independent statement before the code that you intent to protect. ```python assert_valid(x, isfinite): ...<your code> ``` Note: this is a friendly alias for `_validator(base_validator_s)(value)` :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param name: the name of the variable to validate. It will be used in error messages :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. :param error_type: a subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error in case of validation failure :return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError. def assert_valid(name, # type: str value, # type: Any *validation_func, # type: ValidationFuncs **kwargs): """ Validates value `value` using validation function(s) `base_validator_s`. As opposed to `is_valid`, this function raises a `ValidationError` if validation fails. It is therefore designed to be used for defensive programming, in an independent statement before the code that you intent to protect. ```python assert_valid(x, isfinite): ...<your code> ``` Note: this is a friendly alias for `_validator(base_validator_s)(value)` :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param name: the name of the variable to validate. It will be used in error messages :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. :param error_type: a subclass of ValidationError to raise in case of validation failure. By default a ValidationError will be raised with the provided help_msg :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional keyword arguments providing additional context, that will be provided to the error in case of validation failure :return: nothing in case of success. In case of failure, raises a <error_type> if provided, or a ValidationError. """ error_type, help_msg, none_policy = pop_kwargs(kwargs, [('error_type', None), ('help_msg', None), ('none_policy', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs return Validator(*validation_func, error_type=error_type, help_msg=help_msg, none_policy=none_policy).assert_valid(name=name, value=value, **kw_context_args)
Validates value `value` using validation function(s) `validator_func`. As opposed to `assert_valid`, this function returns a boolean indicating if validation was a success or a failure. It is therefore designed to be used within if ... else ... statements: ```python if is_valid(x, isfinite): ...<code> else ...<code> ``` Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)` :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a returned value of False :return: True if validation was a success, False otherwise def is_valid(value, *validation_func, # type: Union[Callable, List[Callable]] **kwargs ): # type: (...) -> bool """ Validates value `value` using validation function(s) `validator_func`. As opposed to `assert_valid`, this function returns a boolean indicating if validation was a success or a failure. It is therefore designed to be used within if ... else ... statements: ```python if is_valid(x, isfinite): ...<code> else ...<code> ``` Note: this is a friendly alias for `return _validator(validator_func, return_bool=True)(value)` :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_` (such as the main list). Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param value: the value to validate :param none_policy: describes how None values should be handled. See `NonePolicy` for the various possibilities. Default is `NonePolicy.VALIDATE`, meaning that None values will be treated exactly like other values and follow the same validation process. Note that errors raised by NonePolicy.FAIL will be caught and transformed into a returned value of False :return: True if validation was a success, False otherwise """ none_policy = pop_kwargs(kwargs, [('none_policy', None)]) return Validator(*validation_func, none_policy=none_policy).is_valid(value)
Creates an instance without using a Validator. This method is not the primary way that errors are created - they should rather created by the validation entry points. However it can be handy in rare edge cases. :param validation_function_name: :param var_name: :param var_value: :param validation_outcome: :param help_msg: :param append_details: :param kw_context_args: :return: def create_manually(cls, validation_function_name, # type: str var_name, # type: str var_value, validation_outcome=None, # type: Any help_msg=None, # type: str append_details=True, # type: bool **kw_context_args): """ Creates an instance without using a Validator. This method is not the primary way that errors are created - they should rather created by the validation entry points. However it can be handy in rare edge cases. :param validation_function_name: :param var_name: :param var_value: :param validation_outcome: :param help_msg: :param append_details: :param kw_context_args: :return: """ # create a dummy validator def val_fun(x): pass val_fun.__name__ = validation_function_name validator = Validator(val_fun, error_type=cls, help_msg=help_msg, **kw_context_args) # create the exception # e = cls(validator, var_value, var_name, validation_outcome=validation_outcome, help_msg=help_msg, # append_details=append_details, **kw_context_args) e = validator._create_validation_error(var_name, var_value, validation_outcome, error_type=cls, help_msg=help_msg, **kw_context_args) return e
The function called to get the details appended to the help message when self.append_details is True def get_details(self): """ The function called to get the details appended to the help message when self.append_details is True """ # create the exception main message according to the type of result if isinstance(self.validation_outcome, Exception): prefix = 'Validation function [{val}] raised ' if self.display_prefix_for_exc_outcomes else '' # new: we now remove "Root validator was [{validator}]", users can get it through e.validator contents = ('Error validating {what}. ' + prefix + '{exception}: {details}')\ .format(what=self.get_what_txt(), val=self.validator.get_main_function_name(), exception=type(self.validation_outcome).__name__, details=end_with_dot(str(self.validation_outcome))) else: contents = 'Error validating {what}: validation function [{val}] returned [{result}].' \ ''.format(what=self.get_what_txt(), val=self.validator.get_main_function_name(), result=self.validation_outcome) # return 'Wrong value: [{}]'.format(self.var_value) return contents
Utility method to get the variable value or 'var_name=value' if name is not None. Note that values with large string representations will not get printed :return: def get_variable_str(self): """ Utility method to get the variable value or 'var_name=value' if name is not None. Note that values with large string representations will not get printed :return: """ if self.var_name is None: prefix = '' else: prefix = self.var_name suffix = str(self.var_value) if len(suffix) == 0: suffix = "''" elif len(suffix) > self.__max_str_length_displayed__: suffix = '' if len(prefix) > 0 and len(suffix) > 0: return prefix + '=' + suffix else: return prefix + suffix
Asserts that the provided named value is valid with respect to the inner base validation functions. It returns silently in case of success, and raises a `ValidationError` or a subclass in case of failure. This corresponds to a 'Defensive programming' (sometimes known as 'Offensive programming') mode. By default this raises instances of `ValidationError` with a default message, in case of failure. There are two ways that you can customize this behaviour: * if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created will be customized with the provided help message. * if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be created. Note that you may still provide a `help_msg`. It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique error type for each kind of applicative error. This eases the process of error handling at app-level. :param name: the name of the variable to validate (for error messages) :param value: the value to validate :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError def assert_valid(self, name, # type: str value, # type: Any error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ Asserts that the provided named value is valid with respect to the inner base validation functions. It returns silently in case of success, and raises a `ValidationError` or a subclass in case of failure. This corresponds to a 'Defensive programming' (sometimes known as 'Offensive programming') mode. By default this raises instances of `ValidationError` with a default message, in case of failure. There are two ways that you can customize this behaviour: * if you set `help_msg` in this method or in `Validator` constructor, instances of `ValidationError` created will be customized with the provided help message. * if you set `error_type` in this method or in `Validator` constructor, instances of your custom class will be created. Note that you may still provide a `help_msg`. It is recommended that Users define their own validation error types (case 2 above), so as to provide a unique error type for each kind of applicative error. This eases the process of error handling at app-level. :param name: the name of the variable to validate (for error messages) :param value: the value to validate :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError """ try: # perform validation res = self.main_function(value) except Exception as e: # caught any exception: raise ValidationError or subclass with that exception in the details # --old bad idea: first wrap into a failure ==> NO !!! I tried and it was making it far too messy/verbose # note: we do not have to 'raise x from e' of `raise_from`since the ValidationError constructor already # sets the __cause__ so we can safely take the same handling than for non-exception failures. res = e # check the result if not result_is_success(res): raise_(self._create_validation_error(name, value, validation_outcome=res, error_type=error_type, help_msg=help_msg, **kw_context_args))
The function doing the final error raising. def _create_validation_error(self, name, # type: str value, # type: Any validation_outcome=None, # type: Any error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ The function doing the final error raising. """ # first merge the info provided in arguments and in self error_type = error_type or self.error_type help_msg = help_msg or self.help_msg ctx = copy(self.kw_context_args) ctx.update(kw_context_args) # allow the class to override the name name = self._get_name_for_errors(name) if issubclass(error_type, TypeError) or issubclass(error_type, ValueError): # this is most probably a custom error type, it is already annotated with ValueError and/or TypeError # so use it 'as is' new_error_type = error_type else: # Add the appropriate TypeError/ValueError base type dynamically additional_type = None if isinstance(validation_outcome, Exception): if is_error_of_type(validation_outcome, TypeError): additional_type = TypeError elif is_error_of_type(validation_outcome, ValueError): additional_type = ValueError if additional_type is None: # not much we can do here, let's assume a ValueError, that is more probable additional_type = ValueError new_error_type = add_base_type_dynamically(error_type, additional_type) # then raise the appropriate ValidationError or subclass return new_error_type(validator=self, var_value=value, var_name=name, validation_outcome=validation_outcome, help_msg=help_msg, **ctx)
Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in the validation process will be silently caught. :param value: the value to validate :return: a boolean flag indicating success or failure def is_valid(self, value # type: Any ): # type: (...) -> bool """ Validates the provided value and returns a boolean indicating success or failure. Any Exception happening in the validation process will be silently caught. :param value: the value to validate :return: a boolean flag indicating success or failure """ # noinspection PyBroadException try: # perform validation res = self.main_function(value) # return a boolean indicating if success or failure return result_is_success(res) except Exception: # caught exception means failure > return False return False
Create a tag. def create_tags(user): """Create a tag.""" values = { 'id': utils.gen_uuid(), 'created_at': datetime.datetime.utcnow().isoformat() } values.update(schemas.tag.post(flask.request.json)) with flask.g.db_conn.begin(): where_clause = sql.and_( _TABLE.c.name == values['name']) query = sql.select([_TABLE.c.id]).where(where_clause) if flask.g.db_conn.execute(query).fetchone(): raise dci_exc.DCIConflict('Tag already exists', values) # create the label/value row query = _TABLE.insert().values(**values) flask.g.db_conn.execute(query) result = json.dumps({'tag': values}) return flask.Response(result, 201, content_type='application/json')
Get all tags. def get_tags(user): """Get all tags.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _T_COLUMNS) nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name) return flask.jsonify({'tags': rows, '_meta': {'count': nb_rows}})
Delete a tag. def delete_tag_by_id(user, tag_id): """Delete a tag.""" query = _TABLE.delete().where(_TABLE.c.id == tag_id) result = flask.g.db_conn.execute(query) if not result.rowcount: raise dci_exc.DCIConflict('Tag deletion conflict', tag_id) return flask.Response(None, 204, content_type='application/json')
Initialize application object. :param app: An instance of :class:`~flask.Flask`. :param entry_point_group: A name of entry point group used to load ``webassets`` bundles. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. def init_app(self, app, entry_point_group='invenio_assets.bundles', **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. :param entry_point_group: A name of entry point group used to load ``webassets`` bundles. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. """ self.init_config(app) self.env.init_app(app) self.collect.init_app(app) self.webpack.init_app(app) if entry_point_group: self.load_entrypoint(entry_point_group) app.extensions['invenio-assets'] = self
Initialize configuration. :param app: An instance of :class:`~flask.Flask`. def init_config(self, app): """Initialize configuration. :param app: An instance of :class:`~flask.Flask`. """ app.config.setdefault('REQUIREJS_BASEURL', app.static_folder) app.config.setdefault('COLLECT_STATIC_ROOT', app.static_folder) app.config.setdefault('COLLECT_STORAGE', 'flask_collect.storage.link') app.config.setdefault( 'COLLECT_FILTER', partial(collect_staticroot_removal, app)) app.config.setdefault( 'WEBPACKEXT_PROJECT', 'invenio_assets.webpack:project')
Load entrypoint. :param entry_point_group: A name of entry point group used to load ``webassets`` bundles. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. def load_entrypoint(self, entry_point_group): """Load entrypoint. :param entry_point_group: A name of entry point group used to load ``webassets`` bundles. .. versionchanged:: 1.0.0b2 The *entrypoint* has been renamed to *entry_point_group*. """ for ep in pkg_resources.iter_entry_points(entry_point_group): self.env.register(ep.name, ep.load())
An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of success, and raises a HasWrongType exception in case of failure. Used in validate and validation/validator :param value: the value to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: def assert_instance_of(value, allowed_types # type: Union[Type, Tuple[Type]] ): """ An inlined version of instance_of(var_types)(value) without 'return True': it does not return anything in case of success, and raises a HasWrongType exception in case of failure. Used in validate and validation/validator :param value: the value to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: """ if not isinstance(value, allowed_types): try: # more than 1 ? allowed_types[1] raise HasWrongType(wrong_value=value, ref_type=allowed_types, help_msg='Value should be an instance of any of {ref_type}') except IndexError: # 1 allowed_types = allowed_types[0] except TypeError: # 1 pass raise HasWrongType(wrong_value=value, ref_type=allowed_types)
An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of success, and raises a IsWrongType exception in case of failure. Used in validate and validation/validator :param typ: the type to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: def assert_subclass_of(typ, allowed_types # type: Union[Type, Tuple[Type]] ): """ An inlined version of subclass_of(var_types)(value) without 'return True': it does not return anything in case of success, and raises a IsWrongType exception in case of failure. Used in validate and validation/validator :param typ: the type to check :param allowed_types: the type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :return: """ if not issubclass(typ, allowed_types): try: # more than 1 ? allowed_types[1] raise IsWrongType(wrong_value=typ, ref_type=allowed_types, help_msg='Value should be a subclass of any of {ref_type}') except IndexError: # 1 allowed_types = allowed_types[0] except TypeError: # 1 pass raise IsWrongType(wrong_value=typ, ref_type=allowed_types)
A validation function for quick inline validation of `value`, with minimal capabilities: * None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False) * Type validation: `value` should be an instance of any of `var_types` if provided * Value validation: * if `allowed_values` is provided, `value` should be in that set * if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True` * if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True` :param name: the applicative name of the checked value, that will be used in error messages :param value: the value to check :param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None. :param equals: an optional value to enforce. :param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param is_in: an optional set of allowed values. :param subset_of: an optional superset for the variable :param contains: an optional value that the variable should contain (value in variable == True) :param superset_of: an optional subset for the variable :param min_value: an optional minimum value :param min_strict: if True, only values strictly greater than `min_value` will be accepted :param max_value: an optional maximum value :param max_strict: if True, only values strictly lesser than `max_value` will be accepted :param length: an optional strict length :param min_len: an optional minimum length :param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted :param max_len: an optional maximum length :param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted :param custom: a custom base validation function or list of base validation functions to use. This is the same syntax than for valid8 decorators. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError def validate(name, # type: str value, # type: Any enforce_not_none=True, # type: bool equals=None, # type: Any instance_of=None, # type: Union[Type, Tuple[Type]] subclass_of=None, # type: Union[Type, Tuple[Type]] is_in=None, # type: Container subset_of=None, # type: Set contains = None, # type: Union[Any, Iterable] superset_of=None, # type: Set min_value=None, # type: Any min_strict=False, # type: bool max_value=None, # type: Any max_strict=False, # type: bool length=None, # type: int min_len=None, # type: int min_len_strict=False, # type: bool max_len=None, # type: int max_len_strict=False, # type: bool custom=None, # type: Callable[[Any], Any] error_type=None, # type: Type[ValidationError] help_msg=None, # type: str **kw_context_args): """ A validation function for quick inline validation of `value`, with minimal capabilities: * None handling: reject None (enforce_not_none=True, default), or accept None silently (enforce_not_none=False) * Type validation: `value` should be an instance of any of `var_types` if provided * Value validation: * if `allowed_values` is provided, `value` should be in that set * if `min_value` (resp. `max_value`) is provided, `value` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_strict`, resp. `max_strict`, to `True` * if `min_len` (resp. `max_len`) is provided, `len(value)` should be greater than it. Comparison is not strict by default and can be set to strict by setting `min_len_strict`, resp. `max_len_strict`, to `True` :param name: the applicative name of the checked value, that will be used in error messages :param value: the value to check :param enforce_not_none: boolean, default True. Whether to enforce that `value` is not None. :param equals: an optional value to enforce. :param instance_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param subclass_of: optional type(s) to enforce. If a tuple of types is provided it is considered alternate types: one match is enough to succeed. If None, type will not be enforced :param is_in: an optional set of allowed values. :param subset_of: an optional superset for the variable :param contains: an optional value that the variable should contain (value in variable == True) :param superset_of: an optional subset for the variable :param min_value: an optional minimum value :param min_strict: if True, only values strictly greater than `min_value` will be accepted :param max_value: an optional maximum value :param max_strict: if True, only values strictly lesser than `max_value` will be accepted :param length: an optional strict length :param min_len: an optional minimum length :param min_len_strict: if True, only values with length strictly greater than `min_len` will be accepted :param max_len: an optional maximum length :param max_len_strict: if True, only values with length strictly lesser than `max_len` will be accepted :param custom: a custom base validation function or list of base validation functions to use. This is the same syntax than for valid8 decorators. A callable, a tuple(callable, help_msg_str), a tuple(callable, failure_type), or a list of several such elements. Nested lists are supported and indicate an implicit `and_`. Tuples indicate an implicit `_failure_raiser`. [mini_lambda](https://smarie.github.io/python-mini-lambda/) expressions can be used instead of callables, they will be transformed to functions automatically. :param error_type: a subclass of `ValidationError` to raise in case of validation failure. By default a `ValidationError` will be raised with the provided `help_msg` :param help_msg: an optional help message to be used in the raised error in case of validation failure. :param kw_context_args: optional contextual information to store in the exception, and that may be also used to format the help message :return: nothing in case of success. Otherwise, raises a ValidationError """ # backwards compatibility instance_of = instance_of or (kw_context_args.pop('allowed_types') if 'allowed_types' in kw_context_args else None) is_in = is_in or (kw_context_args.pop('allowed_values') if 'allowed_values' in kw_context_args else None) try: # the following corresponds to an inline version of # - _none_rejecter in base.py # - gt/lt in comparables.py # - is_in/contains/subset_of/superset_of/has_length/minlen/maxlen/is_in in collections.py # - instance_of/subclass_of in types.py # try (https://github.com/orf/inliner) to perform the inlining below automatically without code duplication ? # > maybe not because quite dangerous (AST mod) and below we skip the "return True" everywhere for performance # # Another alternative: easy Cython compiling https://github.com/AlanCristhian/statically # > but this is not py2 compliant if value is None: # inlined version of _none_rejecter in base.py if enforce_not_none: raise ValueIsNone(wrong_value=value) # raise MissingMandatoryParameterException('Error, ' + name + '" is mandatory, it should be non-None') # else do nothing and return else: if equals is not None: if value != equals: raise NotEqual(wrong_value=value, ref_value=equals) if instance_of is not None: assert_instance_of(value, instance_of) if subclass_of is not None: assert_subclass_of(value, subclass_of) if is_in is not None: # inlined version of is_in(allowed_values=allowed_values)(value) without 'return True' if value not in is_in: raise NotInAllowedValues(wrong_value=value, allowed_values=is_in) if contains is not None: # inlined version of contains(ref_value=contains)(value) without 'return True' if contains not in value: raise DoesNotContainValue(wrong_value=value, ref_value=contains) if subset_of is not None: # inlined version of is_subset(reference_set=subset_of)(value) missing = value - subset_of if len(missing) != 0: raise NotSubset(wrong_value=value, reference_set=subset_of, unsupported=missing) if superset_of is not None: # inlined version of is_superset(reference_set=superset_of)(value) missing = superset_of - value if len(missing) != 0: raise NotSuperset(wrong_value=value, reference_set=superset_of, missing=missing) if min_value is not None: # inlined version of gt(min_value=min_value, strict=min_strict)(value) without 'return True' if min_strict: if not value > min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=True) else: if not value >= min_value: raise TooSmall(wrong_value=value, min_value=min_value, strict=False) if max_value is not None: # inlined version of lt(max_value=max_value, strict=max_strict)(value) without 'return True' if max_strict: if not value < max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=True) else: if not value <= max_value: raise TooBig(wrong_value=value, max_value=max_value, strict=False) if length is not None: # inlined version of has_length() without 'return True' if len(value) != length: raise WrongLength(wrong_value=value, ref_length=length) if min_len is not None: # inlined version of minlen(min_length=min_len, strict=min_len_strict)(value) without 'return True' if min_len_strict: if not len(value) > min_len: raise TooShort(wrong_value=value, min_length=min_len, strict=True) else: if not len(value) >= min_len: raise TooShort(wrong_value=value, min_length=min_len, strict=False) if max_len is not None: # inlined version of maxlen(max_length=max_len, strict=max_len_strict)(value) without 'return True' if max_len_strict: if not len(value) < max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=True) else: if not len(value) <= max_len: raise TooLong(wrong_value=value, max_length=max_len, strict=False) except Exception as e: err = _QUICK_VALIDATOR._create_validation_error(name, value, validation_outcome=e, error_type=error_type, help_msg=help_msg, **kw_context_args) raise_(err) if custom is not None: # traditional custom validator assert_valid(name, value, custom, error_type=error_type, help_msg=help_msg, **kw_context_args) else: # basic (and not enough) check to verify that there was no typo leading an argument to be put in kw_context_args if error_type is None and help_msg is None and len(kw_context_args) > 0: raise ValueError("Keyword context arguments have been provided but help_msg and error_type are not: {}" "".format(kw_context_args))
'Greater than' validation_function generator. Returns a validation_function to check that x >= min_value (strict=False, default) or x > min_value (strict=True) :param min_value: minimum value for x :param strict: Boolean flag to switch between x >= min_value (strict=False) and x > min_value (strict=True) :return: def gt(min_value, # type: Any strict=False # type: bool ): """ 'Greater than' validation_function generator. Returns a validation_function to check that x >= min_value (strict=False, default) or x > min_value (strict=True) :param min_value: minimum value for x :param strict: Boolean flag to switch between x >= min_value (strict=False) and x > min_value (strict=True) :return: """ if strict: def gt_(x): if x > min_value: return True else: # raise Failure('x > ' + str(min_value) + ' does not hold for x=' + str(x)) # '{val} is not strictly greater than {ref}' raise TooSmall(wrong_value=x, min_value=min_value, strict=True) else: def gt_(x): if x >= min_value: return True else: # raise Failure('x >= ' + str(min_value) + ' does not hold for x=' + str(x)) # '{val} is not greater than {ref}' raise TooSmall(wrong_value=x, min_value=min_value, strict=False) gt_.__name__ = '{}greater_than_{}'.format('strictly_' if strict else '', min_value) return gt_
'Lesser than' validation_function generator. Returns a validation_function to check that x <= max_value (strict=False, default) or x < max_value (strict=True) :param max_value: maximum value for x :param strict: Boolean flag to switch between x <= max_value (strict=False) and x < max_value (strict=True) :return: def lt(max_value, # type: Any strict=False # type: bool ): """ 'Lesser than' validation_function generator. Returns a validation_function to check that x <= max_value (strict=False, default) or x < max_value (strict=True) :param max_value: maximum value for x :param strict: Boolean flag to switch between x <= max_value (strict=False) and x < max_value (strict=True) :return: """ if strict: def lt_(x): if x < max_value: return True else: # raise Failure('x < ' + str(max_value) + ' does not hold for x=' + str(x)) # '{val} is not strictly lesser than {ref}' raise TooBig(wrong_value=x, max_value=max_value, strict=True) else: def lt_(x): if x <= max_value: return True else: # raise Failure('x <= ' + str(max_value) + ' does not hold for x=' + str(x)) # '{val} is not lesser than {ref}' raise TooBig(wrong_value=x, max_value=max_value, strict=False) lt_.__name__ = '{}lesser_than_{}'.format('strictly_' if strict else '', max_value) return lt_
'Is between' validation_function generator. Returns a validation_function to check that min_val <= x <= max_val (default). open_right and open_left flags allow to transform each side into strict mode. For example setting open_left=True will enforce min_val < x <= max_val :param min_val: minimum value for x :param max_val: maximum value for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: def between(min_val, # type: Any max_val, # type: Any open_left=False, # type: bool open_right=False # type: bool ): """ 'Is between' validation_function generator. Returns a validation_function to check that min_val <= x <= max_val (default). open_right and open_left flags allow to transform each side into strict mode. For example setting open_left=True will enforce min_val < x <= max_val :param min_val: minimum value for x :param max_val: maximum value for x :param open_left: Boolean flag to turn the left inequality to strict mode :param open_right: Boolean flag to turn the right inequality to strict mode :return: """ if open_left and open_right: def between_(x): if (min_val < x) and (x < max_val): return True else: # raise Failure('{} < x < {} does not hold for x={}'.format(min_val, max_val, x)) raise NotInRange(wrong_value=x, min_value=min_val, left_strict=True, max_value=max_val, right_strict=True) elif open_left: def between_(x): if (min_val < x) and (x <= max_val): return True else: # raise Failure('between: {} < x <= {} does not hold for x={}'.format(min_val, max_val, x)) raise NotInRange(wrong_value=x, min_value=min_val, left_strict=True, max_value=max_val, right_strict=False) elif open_right: def between_(x): if (min_val <= x) and (x < max_val): return True else: # raise Failure('between: {} <= x < {} does not hold for x={}'.format(min_val, max_val, x)) raise NotInRange(wrong_value=x, min_value=min_val, left_strict=False, max_value=max_val, right_strict=True) else: def between_(x): if (min_val <= x) and (x <= max_val): return True else: # raise Failure('between: {} <= x <= {} does not hold for x={}'.format(min_val, max_val, x)) raise NotInRange(wrong_value=x, min_value=min_val, left_strict=False, max_value=max_val, right_strict=False) between_.__name__ = 'between_{}_and_{}'.format(min_val, max_val) return between_
This is the main method for the sub=process, everything we need to create the message pump and channel it needs to be passed in as parameters that can be pickled as when we run they will be serialized into this process. The data should be value types, not reference types as we will receive a copy of the original. Inter-process communication is signalled by the event - to indicate startup - and the pipeline to facilitate a sentinel or stop message :param started_event: Used by the sub-process to signal that it is ready :param channel_name: The name we want to give the channel to the broker for identification :param connection: The 'broker' connection :param consumer_configuration: How to configure our consumer of messages from the channel :param consumer_factory: Callback to create the consumer. User code as we don't know what consumer library they want to use. Arame? Something else? :param command_processor_factory: Callback to register subscribers, policies, and task queues then build command processor. User code that provides us with their requests and handlers :param mapper_func: We need to map between messages on the wire and our handlers :return: def _sub_process_main(started_event: Event, channel_name: str, connection: Connection, consumer_configuration: BrightsideConsumerConfiguration, consumer_factory: Callable[[Connection, BrightsideConsumerConfiguration, logging.Logger], BrightsideConsumer], command_processor_factory: Callable[[str], CommandProcessor], mapper_func: Callable[[BrightsideMessage], Request]) -> None: """ This is the main method for the sub=process, everything we need to create the message pump and channel it needs to be passed in as parameters that can be pickled as when we run they will be serialized into this process. The data should be value types, not reference types as we will receive a copy of the original. Inter-process communication is signalled by the event - to indicate startup - and the pipeline to facilitate a sentinel or stop message :param started_event: Used by the sub-process to signal that it is ready :param channel_name: The name we want to give the channel to the broker for identification :param connection: The 'broker' connection :param consumer_configuration: How to configure our consumer of messages from the channel :param consumer_factory: Callback to create the consumer. User code as we don't know what consumer library they want to use. Arame? Something else? :param command_processor_factory: Callback to register subscribers, policies, and task queues then build command processor. User code that provides us with their requests and handlers :param mapper_func: We need to map between messages on the wire and our handlers :return: """ logger = logging.getLogger(__name__) consumer = consumer_factory(connection, consumer_configuration, logger) channel = Channel(name=channel_name, consumer=consumer, pipeline=consumer_configuration.pipeline) # TODO: Fix defaults that need passed in config values command_processor = command_processor_factory(channel_name) message_pump = MessagePump(command_processor=command_processor, channel=channel, mapper_func=mapper_func, timeout=500, unacceptable_message_limit=None, requeue_count=None) logger.debug("Starting the message pump for %s", channel_name) message_pump.run(started_event)
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ app_conf = dci_config.generate_conf() url = app_conf['SQLALCHEMY_DATABASE_URI'] context.configure( url=url, target_metadata=target_metadata, literal_binds=True, ) with context.begin_transaction(): context.run_migrations()
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ app_conf = dci_config.generate_conf() connectable = dci_config.get_engine(app_conf) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, ) with context.begin_transaction(): context.run_migrations()
Sends a 401 reject response that enables basic auth. def reject(): """Sends a 401 reject response that enables basic auth.""" auth_message = ('Could not verify your access level for that URL.' 'Please login with proper credentials.') auth_message = json.dumps({'_status': 'Unauthorized', 'message': auth_message}) headers = {'WWW-Authenticate': 'Basic realm="Login required"'} return flask.Response(auth_message, 401, headers=headers, content_type='application/json')
Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String def modify(self, **kwargs): """Modify a contact. Returns status message Optional Parameters: * name -- Contact name Type: String * email -- Contact email address Type: String * cellphone -- Cellphone number, without the country code part. In some countries you are supposed to exclude leading zeroes. (Requires countrycode and countryiso) Type: String * countrycode -- Cellphone country code (Requires cellphone and countryiso) Type: String * countryiso -- Cellphone country ISO code. For example: US (USA), GB (Britain) or SE (Sweden) (Requires cellphone and countrycode) Type: String * defaultsmsprovider -- Default SMS provider Type: String ['clickatell', 'bulksms', 'esendex', 'cellsynt'] * directtwitter -- Send tweets as direct messages Type: Boolean Default: True * twitteruser -- Twitter user Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['email', 'cellphone', 'countrycode', 'countryiso', 'defaultsmsprovider', 'directtwitter', 'twitteruser', 'name']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of <PingdomContact>.modify()\n') response = self.pingdom.request('PUT', 'notification_contacts/%s' % self.id, kwargs) return response.json()['message']
We don't use a pool here. We only have one consumer connection per process, so we get no value from a pool, and we want to use a heartbeat to keep the consumer collection alive, which does not work with a pool :return: the connection to the transport def _establish_connection(self, conn: BrokerConnection) -> None: """ We don't use a pool here. We only have one consumer connection per process, so we get no value from a pool, and we want to use a heartbeat to keep the consumer collection alive, which does not work with a pool :return: the connection to the transport """ try: self._logger.debug("Establishing connection.") self._conn = conn.ensure_connection(max_retries=3) self._logger.debug('Got connection: %s', conn.as_uri()) except kombu_exceptions.OperationalError as oe: self._logger.error("Error connecting to RMQ, could not retry %s", oe) # Try to clean up the mess if self._conn is not None: self._conn.close() else: conn.close()
For a long runing handler, there is a danger that we do not send a heartbeat message or activity on the connection whilst we are running the handler. With a default heartbeat of 30s, for example, there is a risk that a handler which takes more than 15s will fail to send the heartbeat in time and then the broker will reset the connection. So we spin up another thread, where the user has marked the thread as having a long-running thread :return: an event to cancel the thread def run_heartbeat_continuously(self) -> threading.Event: """ For a long runing handler, there is a danger that we do not send a heartbeat message or activity on the connection whilst we are running the handler. With a default heartbeat of 30s, for example, there is a risk that a handler which takes more than 15s will fail to send the heartbeat in time and then the broker will reset the connection. So we spin up another thread, where the user has marked the thread as having a long-running thread :return: an event to cancel the thread """ cancellation_event = threading.Event() # Effectively a no-op if we are not actually a long-running thread if not self._is_long_running_handler: return cancellation_event self._logger.debug("Running long running handler on %s", self._conn) def _send_heartbeat(cnx: BrokerConnection, period: int, logger: logging.Logger) -> None: while not cancellation_event.is_set(): cnx.heartbeat_check() time.sleep(period) logger.debug("Signalled to exit long-running handler heartbeat") heartbeat_thread = threading.Thread(target=_send_heartbeat, args=(self._conn, 1, self._logger), daemon=True) self._logger.debug("Begin heartbeat thread for %s", self._conn) heartbeat_thread.start() self._logger.debug("Heartbeat running on thread for %s", self._conn) return cancellation_event
If the topic has it's export_control set to True then all the teams under the product team can access to the topic's resources. :param user: :param topic: :return: True if check is ok, False otherwise def _check(user, topic): """If the topic has it's export_control set to True then all the teams under the product team can access to the topic's resources. :param user: :param topic: :return: True if check is ok, False otherwise """ # if export_control then check the team is associated to the product, ie.: # - the current user belongs to the product's team # OR # - the product's team belongs to the user's parents teams if topic['export_control']: product = v1_utils.verify_existence_and_get(topic['product_id'], models.PRODUCTS) return (user.is_in_team(product['team_id']) or product['team_id'] in user.parent_teams_ids) return False
Ensure the proper content is uploaded. Stream might be already consumed by authentication process. Hence flask.request.stream might not be readable and return improper value. This methods checks if the stream has already been consumed and if so retrieve the data from flask.request.data where it has been stored. def get_stream_or_content_from_request(request): """Ensure the proper content is uploaded. Stream might be already consumed by authentication process. Hence flask.request.stream might not be readable and return improper value. This methods checks if the stream has already been consumed and if so retrieve the data from flask.request.data where it has been stored. """ if request.stream.tell(): logger.info('Request stream already consumed. ' 'Storing file content using in-memory data.') return request.data else: logger.info('Storing file content using request stream.') return request.stream
Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix name '_' so it can be used despite empty namespace prefixes being unsupported by XPath. def xpath_on_node(self, node, xpath, **kwargs): """ Return result of performing the given XPath query on the given node. All known namespace prefix-to-URI mappings in the document are automatically included in the XPath invocation. If an empty/default namespace (i.e. None) is defined, this is converted to the prefix name '_' so it can be used despite empty namespace prefixes being unsupported by XPath. """ if isinstance(node, etree._ElementTree): # Document node lxml.etree._ElementTree has no nsmap, lookup root root = self.get_impl_root(node) namespaces_dict = root.nsmap.copy() else: namespaces_dict = node.nsmap.copy() if 'namespaces' in kwargs: namespaces_dict.update(kwargs['namespaces']) # Empty namespace prefix is not supported, convert to '_' prefix if None in namespaces_dict: default_ns_uri = namespaces_dict.pop(None) namespaces_dict['_'] = default_ns_uri # Include XMLNS namespace if it's not already defined if not 'xmlns' in namespaces_dict: namespaces_dict['xmlns'] = nodes.Node.XMLNS_URI return node.xpath(xpath, namespaces=namespaces_dict)
Return True if the given namespace name/value is defined in an ancestor of the given node, meaning that the given node need not have its own attributes to apply that namespacing. def _is_ns_in_ancestor(self, node, name, value): """ Return True if the given namespace name/value is defined in an ancestor of the given node, meaning that the given node need not have its own attributes to apply that namespacing. """ curr_node = self.get_node_parent(node) while curr_node.__class__ == etree._Element: if (hasattr(curr_node, 'nsmap') and curr_node.nsmap.get(name) == value): return True for n, v in curr_node.attrib.items(): if v == value and '{%s}' % nodes.Node.XMLNS_URI in n: return True curr_node = self.get_node_parent(curr_node) return False
Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation def generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field=None, alias='score'): """ Find blog entries with the most comments: qs = generic_annotate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) for entry in qs: print entry.title, entry.score Find the highest rated foods: generic_annotate(Food, Rating, Avg('ratings__rating'), alias='avg') for food in qs: print food.name, '- average rating:', food.avg .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk :param alias: attribute name to use for annotation """ return fallback_generic_annotate(qs_model, generic_qs_model, aggregator, gfk_field, alias)
Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk def generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field=None): """ Find total number of comments on blog entries: generic_aggregate(Entry.objects.public(), Comment.objects.public(), Count('comments__id')) Find the average rating for foods starting with 'a': a_foods = Food.objects.filter(name__startswith='a') generic_aggregate(a_foods, Rating, Avg('ratings__rating')) .. note:: In both of the above examples it is assumed that a GenericRelation exists on Entry to Comment (named "comments") and also on Food to Rating (named "ratings"). If a GenericRelation does *not* exist, the query will still return correct results but the code path will be different as it will use the fallback method. .. warning:: If the underlying column type differs between the qs_model's primary key and the generic_qs_model's foreign key column, it will use the fallback method, which can correctly CASTself. :param qs_model: A model or a queryset of objects you want to perform annotation on, e.g. blog entries :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param aggregator: an aggregation, from django.db.models, e.g. Count('id') or Avg('rating') :param gfk_field: explicitly specify the field w/the gfk """ return fallback_generic_aggregate(qs_model, generic_qs_model, aggregator, gfk_field)
Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk def generic_filter(generic_qs_model, filter_qs_model, gfk_field=None): """ Only show me ratings made on foods that start with "a": a_foods = Food.objects.filter(name__startswith='a') generic_filter(Rating.objects.all(), a_foods) Only show me comments from entries that are marked as public: generic_filter(Comment.objects.public(), Entry.objects.public()) :param generic_qs_model: A model or queryset containing a GFK, e.g. comments :param qs_model: A model or a queryset of objects you want to restrict the generic_qs to :param gfk_field: explicitly specify the field w/the gfk """ generic_qs = normalize_qs_model(generic_qs_model) filter_qs = normalize_qs_model(filter_qs_model) if not gfk_field: gfk_field = get_gfk_field(generic_qs.model) pk_field_type = get_field_type(filter_qs.model._meta.pk) gfk_field_type = get_field_type(generic_qs.model._meta.get_field(gfk_field.fk_field)) if pk_field_type != gfk_field_type: return fallback_generic_filter(generic_qs, filter_qs, gfk_field) return generic_qs.filter(**{ gfk_field.ct_field: ContentType.objects.get_for_model(filter_qs.model), '%s__in' % gfk_field.fk_field: filter_qs.values('pk'), })
Generate random etag based on MD5. def gen_etag(): """Generate random etag based on MD5.""" my_salt = gen_uuid() if six.PY2: my_salt = my_salt.decode('utf-8') elif six.PY3: my_salt = my_salt.encode('utf-8') md5 = hashlib.md5() md5.update(my_salt) return md5.hexdigest()
Delete this email report def delete(self): """Delete this email report""" response = self.pingdom.request('DELETE', 'reports.shared/%s' % self.id) return response.json()['message']
Validates that x is a multiple of the reference (`x % ref == 0`) def is_multiple_of(ref): """ Validates that x is a multiple of the reference (`x % ref == 0`) """ def is_multiple_of_ref(x): if x % ref == 0: return True else: raise IsNotMultipleOf(wrong_value=x, ref=ref) # raise Failure('x % {ref} == 0 does not hold for x={val}'.format(ref=ref, val=x)) is_multiple_of_ref.__name__ = 'is_multiple_of_{}'.format(ref) return is_multiple_of_ref
Get all components of a topic. def get_all_components(user, topic_id): """Get all components of a topic.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _C_COLUMNS) query.add_extra_condition(sql.and_( _TABLE.c.topic_id == topic_id, _TABLE.c.state != 'archived')) nb_rows = query.get_number_of_rows() rows = query.execute(fetchall=True) rows = v1_utils.format_result(rows, _TABLE.name, args['embed'], _EMBED_MANY) # Return only the component which have the export_control flag set to true # if user.is_not_super_admin(): rows = [row for row in rows if row['export_control']] return flask.jsonify({'components': rows, '_meta': {'count': nb_rows}})
Returns the component types of a topic. def get_component_types_from_topic(topic_id, db_conn=None): """Returns the component types of a topic.""" db_conn = db_conn or flask.g.db_conn query = sql.select([models.TOPICS]).\ where(models.TOPICS.c.id == topic_id) topic = db_conn.execute(query).fetchone() topic = dict(topic) return topic['component_types']