INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Download a file into the correct cache directory.
def download(cls, url, filename=None): """ Download a file into the correct cache directory. """ return utility.download(url, cls.directory(), filename)
Path that should be used for caching. Different for all subclasses.
def directory(cls, prefix=None): """ Path that should be used for caching. Different for all subclasses. """ prefix = prefix or utility.read_config().directory name = cls.__name__.lower() directory = os.path.expanduser(os.path.join(prefix, name)) utility.ensure_di...
Get the rconfiguration_id of the last job run by the remoteci.
def get_last_rconfiguration_id(topic_id, remoteci_id, db_conn=None): """Get the rconfiguration_id of the last job run by the remoteci. :param topic_id: the topic :param remoteci_id: the remoteci id :return: last rconfiguration_id of the remoteci """ db_conn = db_conn or flask.g.db_conn __TA...
Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.
def get_remoteci_configuration(topic_id, remoteci_id, db_conn=None): """Get a remoteci configuration. This will iterate over each configuration in a round robin manner depending on the last rconfiguration used by the remoteci.""" db_conn = db_conn or flask.g.db_conn last_rconfiguration_id = get_las...
Dispatches a request. Expects one and one only target handler: param request: The request to dispatch: return: None will throw a ConfigurationException if more than one handler factor is registered for the command
def send(self, request: Request) -> None: """ Dispatches a request. Expects one and one only target handler :param request: The request to dispatch :return: None, will throw a ConfigurationException if more than one handler factor is registered for the command """ handle...
Dispatches a request. Expects zero or more target handlers: param request: The request to dispatch: return: None.
def publish(self, request: Request) -> None: """ Dispatches a request. Expects zero or more target handlers :param request: The request to dispatch :return: None. """ handler_factories = self._registry.lookup(request) for factory in handler_factories: ...
Dispatches a request over middleware. Returns when message put onto outgoing channel by producer does not wait for response from a consuming application i. e. is fire - and - forget: param request: The request to dispatch: return: None
def post(self, request: Request) -> None: """ Dispatches a request over middleware. Returns when message put onto outgoing channel by producer, does not wait for response from a consuming application i.e. is fire-and-forget :param request: The request to dispatch :return: None ...
Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents.
def ignore_whitespace_text_nodes(cls, wrapped_node): """ Find and delete any text nodes containing nothing but whitespace in in the given node and its descendents. This is useful for cleaning up excess low-value text nodes in a document DOM after parsing a pretty-printed XML doc...
Return a three - element tuple with the prefix local name and namespace URI for the given element/ attribute name ( in the context of the given node s hierarchy ). If the name has no associated prefix or namespace information None is return for those tuple members.
def get_ns_info_from_node_name(self, name, impl_node): """ Return a three-element tuple with the prefix, local name, and namespace URI for the given element/attribute name (in the context of the given node's hierarchy). If the name has no associated prefix or namespace informatio...
: return: a builder representing an ancestor of the current element by default the parent element.
def up(self, count=1, to_name=None): """ :return: a builder representing an ancestor of the current element, by default the parent element. :param count: return the n'th ancestor element; defaults to 1 which means the immediate parent. If *count* is greater than the...
Add a child element to the: class: xml4h. nodes. Element node represented by this Builder.
def element(self, *args, **kwargs): """ Add a child element to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: a new Builder that represents the child element. Delegates to :meth:`xml4h.nodes.Element.add_element`. """ child_element = ...
Add one or more attributes to the: class: xml4h. nodes. Element node represented by this Builder.
def attributes(self, *args, **kwargs): """ Add one or more attributes to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_attributes`. """ self._element.set_attributes(*a...
Add a processing instruction node to the: class: xml4h. nodes. Element node represented by this Builder.
def processing_instruction(self, target, data): """ Add a processing instruction node to the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.add_instruction`. """ self._element....
Set the namespace prefix of the: class: xml4h. nodes. Element node represented by this Builder.
def ns_prefix(self, prefix, ns_uri): """ Set the namespace prefix of the :class:`xml4h.nodes.Element` node represented by this Builder. :return: the current Builder. Delegates to :meth:`xml4h.nodes.Element.set_ns_prefix`. """ self._element.set_ns_prefix(prefix, ...
Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing default is sha256 ** name - The name of the subject of the request possible arguments are: C - Country name ST - State or province name L - Locality name O - Organization name OU - Organiza...
def createCertRequest(pkey, digest="sha256"): """ Create a certificate request. Arguments: pkey - The key to associate with the request digest - Digestion method to use for signing, default is sha256 **name - The name of the subject of the request, possible ...
Verify the existence of a resource in the database and then return it if it exists according to the condition or raise an exception.
def verify_existence_and_get(id, table, name=None, get_id=False): """Verify the existence of a resource in the database and then return it if it exists, according to the condition, or raise an exception. :param id: id of the resource :param table: the table object :param name: the name of the r...
Retrieve the list of topics IDs a user has access to.
def user_topic_ids(user): """Retrieve the list of topics IDs a user has access to.""" if user.is_super_admin() or user.is_read_only_user(): query = sql.select([models.TOPICS]) else: query = (sql.select([models.JOINS_TOPICS_TEAMS.c.topic_id]) .select_from( ...
Verify that the user s team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics.
def verify_team_in_topic(user, topic_id): """Verify that the user's team does belongs to the given topic. If the user is an admin or read only user then it belongs to all topics. """ if user.is_super_admin() or user.is_read_only_user(): return if str(topic_id) not in user_topic_ids(user): ...
Transform sqlalchemy source: [ { a_id: id1 a_name: name1 b_id: id2 b_name: name2 } { a_id: id3 a_name: name3 b_id: id4 b_name: name4 } ] to [ { id: id1 name: name2 b: { id: id2 name: name2 } { id: id3 name: name3 b: { id: id4 name: name4 } ]
def _format_level_1(rows, root_table_name): """ Transform sqlalchemy source: [{'a_id' : 'id1', 'a_name' : 'name1, 'b_id' : 'id2', 'b_name' : 'name2}, {'a_id' : 'id3', 'a_name' : 'name3, 'b_id' : 'id4', 'b_name' : 'name4} ] to [{'id' : 'id1', 'name':...
From the _format_level_1 function we have a list of rows. Because of using joins we have as many rows as join result.
def _format_level_2(rows, list_embeds, embed_many): """ From the _format_level_1 function we have a list of rows. Because of using joins, we have as many rows as join result. For example: [{'id' : 'id1', 'name' : 'name1, 'b' : {'id': 'id2, 'name': 'name2'} } {'id'...
Build a basic values object used in every create method.
def common_values_dict(): """Build a basic values object used in every create method. All our resources contain a same subset of value. Instead of redoing this code everytime, this method ensures it is done only at one place. """ now = datetime.datetime.utcnow().isoformat() etag = ...
: param fetchall: get all rows: param fetchone: get only one row: param use_labels: prefix row columns names by the table name: return:
def execute(self, fetchall=False, fetchone=False, use_labels=True): """ :param fetchall: get all rows :param fetchone: get only one row :param use_labels: prefix row columns names by the table name :return: """ query = self.get_query(use_labels=use_labels) ...
Returns some information about the currently authenticated identity
def get_identity(identity): """Returns some information about the currently authenticated identity""" return flask.Response( json.dumps( { 'identity': { 'id': identity.id, 'etag': identity.etag, 'name': identity.name...
Get all issues for a specific job.
def get_issues_by_resource(resource_id, table): """Get all issues for a specific job.""" v1_utils.verify_existence_and_get(resource_id, table) # When retrieving the issues for a job, we actually retrieve # the issues attach to the job itself + the issues attached to # the components the job has be...
Unattach an issue from a specific job.
def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, ...
Attach an issue to a specific job.
def attach_issue(resource_id, table, user_id): """Attach an issue to a specific job.""" data = schemas.issue.post(flask.request.json) issue = _get_or_create_issue(data) # Second, insert a join record in the JOIN_JOBS_ISSUES or # JOIN_COMPONENTS_ISSUES database. if table.name == 'jobs': ...
Remove collect s static root folder from list.
def collect_staticroot_removal(app, blueprints): """Remove collect's static root folder from list.""" collect_root = app.extensions['collect'].static_root return [bp for bp in blueprints if ( bp.has_static_folder and bp.static_folder != collect_root)]
Get all jobstates.
def get_all_jobstates(user, job_id): """Get all jobstates. """ args = schemas.args(flask.request.args.to_dict()) job = v1_utils.verify_existence_and_get(job_id, models.JOBS) if user.is_not_super_admin() and user.is_not_read_only_user(): if (job['team_id'] not in user.teams_ids and ...
Create the dci client in the master realm.
def create_client(access_token): """Create the dci client in the master realm.""" url = 'http://keycloak:8080/auth/admin/realms/dci-test/clients' r = requests.post(url, data=json.dumps(client_data), headers=get_auth_headers(access_token)) if r.status_code in (...
Create the a dci user. username = dci password = dci email = dci
def create_user_dci(access_token): """Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io""" user_data = {'username': 'dci', 'email': 'dci@distributed-ci.io', 'enabled': True, 'emailVerified': True, 'credentials':...
The name of the site.: str | None
def initialize(self, name=None, dbname=None, base=None, generator=None, case=None, namespaces=None): self.name = none_or(name, str) """ The name of the site. : str | `None` """ self.dbname = none_or(dbname, str) """ The dbname of the site. : s...
Convert all booleans to lowercase strings
def _serializeBooleans(params): """"Convert all booleans to lowercase strings""" serialized = {} for name, value in params.items(): if value is True: value = 'true' elif value is False: value = 'false' serialized[name] = value ...
Requests wrapper function
def request(self, method, url, parameters=dict()): """Requests wrapper function""" # The requests library uses urllib, which serializes to "True"/"False" while Pingdom requires lowercase parameters = self._serializeBooleans(parameters) headers = {'App-Key': self.apikey} if self...
Returns a list of actions ( alerts ) that have been generated for your account.
def actions(self, **parameters): """Returns a list of actions (alerts) that have been generated for your account. Optional Parameters: * from -- Only include actions generated later than this timestamp. Format is UNIX time. Type: Integer ...
Pulls all checks from pingdom
def getChecks(self, **parameters): """Pulls all checks from pingdom Optional Parameters: * limit -- Limits the number of returned probes to the specified quantity. Type: Integer (max 25000) Default: 25000 * offset -- Offs...
Returns a detailed description of a specified check.
def getCheck(self, checkid): """Returns a detailed description of a specified check.""" check = PingdomCheck(self, {'id': checkid}) check.getDetails() return check
Returns a list of all Pingdom probe servers
def probes(self, **kwargs): """Returns a list of all Pingdom probe servers Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). ...
Perform a traceroute to a specified target from a specified Pingdom probe.
def traceroute(self, host, probeid): """Perform a traceroute to a specified target from a specified Pingdom probe. Provide hostname to check and probeid to check from Returned structure: { 'result' : <String> Traceroute output 'probeid'...
Returns a list of all contacts.
def getContacts(self, **kwargs): """Returns a list of all contacts. Optional Parameters: * limit -- Limits the number of returned contacts to the specified quantity. Type: Integer Default: 100 * offset -- Offset for listi...
Create a new contact.
def newContact(self, name, **kwargs): """Create a new contact. Provide new contact name and any optional arguments. Returns new PingdomContact instance Optional Parameters: * email -- Contact email address Type: String * cellphone -- Ce...
Modifies a list of contacts.
def modifyContacts(self, contactids, paused): """Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message """ response = self.request("PUT", "notification_contacts", {'contactids': contactids, ...
Returns a list of PingdomEmailReport instances.
def getEmailReports(self): """Returns a list of PingdomEmailReport instances.""" reports = [PingdomEmailReport(self, x) for x in self.request('GET', 'reports.email').json()['subscriptions']] return reports
Creates a new email report
def newEmailReport(self, name, **kwargs): """Creates a new email report Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -...
Returns a list of PingdomSharedReport instances
def getSharedReports(self): """Returns a list of PingdomSharedReport instances""" response = self.request('GET', 'reports.shared').json()['shared']['banners'] reports = [PingdomSharedReport(self, x) for x in response] return reports
Create a shared report ( banner ).
def newSharedReport(self, checkid, **kwargs): """Create a shared report (banner). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Typ...
When bool_encry is True encrypt the data with master key. When it is False the function extract the three nonce from the encrypted data ( first 3 * 21 bytes ) and decrypt the data.: param data: the data to encrypt or decrypt.: param masterkey: a 32 bytes key in bytes.: param bool_encry: if bool_encry is True data is en...
def encry_decry_cascade(data, masterkey, bool_encry, assoc_data): """ When bool_encry is True, encrypt the data with master key. When it is False, the function extract the three nonce from the encrypted data (first 3*21 bytes), and decrypt the data. :param data: the data to encrypt or decrypt. :para...
Register the handler for the command: param request_class: The command or event to dispatch. It must implement getKey (): param handler_factory: A factory method to create the handler to dispatch to: return:
def register(self, request_class: Request, handler_factory: Callable[[], Handler]) -> None: """ Register the handler for the command :param request_class: The command or event to dispatch. It must implement getKey() :param handler_factory: A factory method to create the handler to dispat...
Looks up the handler associated with a request - matches the key on the request to a registered handler: param request: The request we want to find a handler for: return:
def lookup(self, request: Request) -> List[Callable[[], Handler]]: """ Looks up the handler associated with a request - matches the key on the request to a registered handler :param request: The request we want to find a handler for :return: """ key = request.__class__.__...
Adds a message mapper to a factory using the requests key: param mapper_func: A callback that creates a BrightsideMessage from a Request: param request_class: A request type
def register(self, request_class: Request, mapper_func: Callable[[Request], BrightsideMessage]) -> None: """Adds a message mapper to a factory, using the requests key :param mapper_func: A callback that creates a BrightsideMessage from a Request :param request_class: A request type """ ...
Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class for sending on the wire: param request_class:: return:
def lookup(self, request_class: Request) -> Callable[[Request], BrightsideMessage]: """ Looks up the message mapper function associated with this class. Function should take in a Request derived class and return a BrightsideMessage derived class, for sending on the wire :param request_c...
This type validation function can be used in two modes: * providing two arguments ( x ref_type ) it returns True if isinstance ( x ref_type ) and raises a HasWrongType error if not. If ref_type is a set of types any match with one of the included types will do * providing a single argument ( ref_type ) this is a functi...
def instance_of(*args): """ This type validation function can be used in two modes: * providing two arguments (x, ref_type), it returns `True` if isinstance(x, ref_type) and raises a HasWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * provi...
This type validation function can be used in two modes: * providing two arguments ( c ref_type ) it returns True if issubclass ( c ref_type ) and raises a IsWrongType error if not. If ref_type is a set of types any match with one of the included types will do * providing a single argument ( ref_type ) this is a functio...
def subclass_of(*args): """ This type validation function can be used in two modes: * providing two arguments (c, ref_type), it returns `True` if issubclass(c, ref_type) and raises a IsWrongType error if not. If ref_type is a set of types, any match with one of the included types will do * provid...
Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If method skip the first argument usually being self or cls. The cache filepath is directory/ basename - hash. pickle.
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.p...
Download a file and return its filename on the local file system. If the file is already there it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath.
def download(url, directory, filename=None): """ Download a file and return its filename on the local file system. If the file is already there, it will not be downloaded again. The filename is derived from the url if not provided. Return the filepath. """ if not filename: _, filename = ...
Create the directories along the provided directory path that do not exist.
def ensure_directory(directory): """ Create the directories along the provided directory path that do not exist. """ directory = os.path.expanduser(directory) try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise e
This function handles the various ways that users may enter validation functions so as to output a single callable method. Setting auto_and_wrapper to False allows callers to get a list of callables instead.
def _process_validation_function_s(validation_func, # type: ValidationFuncs auto_and_wrapper=True # type: bool ): # type: (...) -> Union[Callable, List[Callable]] """ This function handles the various ways that users may enter 'val...
An and validator: it returns True if all of the provided validators return True or raises a AtLeastOneFailed failure on the first False received or Exception caught.
def and_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'and' validator: it returns `True` if all of the provided validators return `True`, or raises a `AtLeastOneFailed` failure on the first `False` received or `Exception` caught. Note that an implicit `and_...
Generates the inverse of the provided validation functions: when the validator returns False or raises a Failure this function returns True. Otherwise it raises a DidNotFail failure.
def not_(validation_func, # type: ValidationFuncs catch_all=False # type: bool ): # type: (...) -> Callable """ Generates the inverse of the provided validation functions: when the validator returns `False` or raises a `Failure`, this function returns `True`. Otherwise it raises a `...
An or validator: returns True if at least one of the provided validators returns True. All exceptions will be silently caught. In case of failure a global AllValidatorsFailed failure will be raised together with details about all validation results.
def or_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ An 'or' validator: returns `True` if at least one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `AllValidatorsFailed` failure will be raised, toget...
A xor validation function: returns True if exactly one of the provided validators returns True. All exceptions will be silently caught. In case of failure a global XorTooManySuccess or AllValidatorsFailed will be raised together with details about the various validation results.
def xor_(*validation_func # type: ValidationFuncs ): # type: (...) -> Callable """ A 'xor' validation function: returns `True` if exactly one of the provided validators returns `True`. All exceptions will be silently caught. In case of failure, a global `XorTooManySuccess` or `AllValidatorsFai...
An alias for not_ ( and_ ( validators )).
def not_all(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ An alias for not_(and_(validators)). :param validation_func: the base validation function or list of base validation functions to use. A callable, a tuple(callable, help_msg_...
This function is automatically used if you provide a tuple ( <function > <msg > _or_<Failure_type > ) to any of the methods in this page or to one of the valid8 decorators. It transforms the provided <function > into a failure raiser raising a subclass of Failure in case of failure ( either not returning True or raisin...
def failure_raiser(*validation_func, # type: ValidationFuncs **kwargs ): # type: (...) -> Callable """ This function is automatically used if you provide a tuple `(<function>, <msg>_or_<Failure_type>)`, to any of the methods in this page or to one of the `valid8` ...
Internal utility method to extract optional arguments from kwargs.
def pop_kwargs(kwargs, names_with_defaults, # type: List[Tuple[str, Any]] allow_others=False ): """ Internal utility method to extract optional arguments from kwargs. :param kwargs: :param names_with_defaults: :param allow_others: if False (default) the...
Overrides the base method in order to give details on the various successes and failures
def get_details(self): """ Overrides the base method in order to give details on the various successes and failures """ # transform the dictionary of failures into a printable form need_to_print_value = True failures_for_print = OrderedDict() for validator, failure in self.failu...
Utility method to play all the provided validators on the provided value and output the
def play_all_validators(self, validators, value): """ Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return: """ successes = list() failures = OrderedDict() for validator i...
Generates a secret of given length
def gen_secret(length=64): """ Generates a secret of given length """ charset = string.ascii_letters + string.digits return ''.join(random.SystemRandom().choice(charset) for _ in range(length))
Encrypt a file and write it with. cryptoshop extension.: param filename: a string with the path to the file to encrypt.: param passphrase: a string with the user passphrase.: param algo: a string with the algorithm. Can be srp aes twf. Default is srp.: return: a string with successfully encrypted or error.
def encryptfile(filename, passphrase, algo='srp'): """ Encrypt a file and write it with .cryptoshop extension. :param filename: a string with the path to the file to encrypt. :param passphrase: a string with the user passphrase. :param algo: a string with the algorithm. Can be srp, aes, twf. Default...
Decrypt a file and write corresponding decrypted file. We remove the. cryptoshop extension.: param filename: a string with the path to the file to decrypt.: param passphrase: a string with the user passphrase.: return: a string with successfully decrypted or error.
def decryptfile(filename, passphrase): """ Decrypt a file and write corresponding decrypted file. We remove the .cryptoshop extension. :param filename: a string with the path to the file to decrypt. :param passphrase: a string with the user passphrase. :return: a string with "successfully decrypted"...
Split a sentence while preserving tags.
def _tokenize(cls, sentence): """ Split a sentence while preserving tags. """ while True: match = cls._regex_tag.search(sentence) if not match: yield from cls._split(sentence) return chunk = sentence[:match.start()] ...
Implements a distributed stategy for processing XML files. This function constructs a set of py: mod: multiprocessing threads ( spread over multiple cores ) and uses an internal queue to aggregate outputs. To use this function implement a process () function that takes two arguments -- a: class: mwxml. Dump and the pat...
def map(process, paths, threads=None): """ Implements a distributed stategy for processing XML files. This function constructs a set of py:mod:`multiprocessing` threads (spread over multiple cores) and uses an internal queue to aggregate outputs. To use this function, implement a `process()` funct...
Return the object itself.
def dump(self): """Return the object itself.""" return { 'title': self.title, 'issue_id': self.issue_id, 'reporter': self.reporter, 'assignee': self.assignee, 'status': self.status, 'product': self.product, 'component':...
Applies func_to_apply on each argument of func according to what s received in current call ( cur_args cur_kwargs ). For each argument of func named att in its signature the following method is called:
def apply_on_each_func_args_sig(func, cur_args, cur_kwargs, sig, # type: Signature func_to_apply, func_to_apply_params_dict): """ Applies func_to_apply...
Ensure the user is a PRODUCT_OWNER.
def is_product_owner(self, team_id): """Ensure the user is a PRODUCT_OWNER.""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.child_teams_ids
Test if user is in team
def is_in_team(self, team_id): """Test if user is in team""" if self.is_super_admin(): return True team_id = uuid.UUID(str(team_id)) return team_id in self.teams or team_id in self.child_teams_ids
Ensure ther resource has the role REMOTECI.
def is_remoteci(self, team_id=None): """Ensure ther resource has the role REMOTECI.""" if team_id is None: return self._is_remoteci team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return self.teams[team_id]['role'] == 'REMO...
Ensure ther resource has the role FEEDER.
def is_feeder(self, team_id=None): """Ensure ther resource has the role FEEDER.""" if team_id is None: return self._is_feeder team_id = uuid.UUID(str(team_id)) if team_id not in self.teams_ids: return False return self.teams[team_id]['role'] == 'FEEDER'
: 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, s...
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] ret...
: 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.
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`. """ re...
: 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.imp...
: 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:...
Delete this node from the owning document.
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. """ ...
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.
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 li...
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.
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" n...
Find: class: Element node descendants of this node with optional constraints to limit the results.
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. ...
Find the first: class: Element node descendant of this node that matches any optional constraints or None if there are no matching elements.
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.fi...
Find: class: Element node descendants of the document containing this node with optional constraints to limit the results.
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 sel...
Serialize this node and its descendants to text writing the output to a given * writer * or to stdout.
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 st...
: return: this node as XML text.
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.
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 ...
Add or update this element s attributes where attributes can be specified in a number of ways.
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 ...
Get or set this element s attributes as name/ value pairs.
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...
: 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, sel...
: 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
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 :...
Define a namespace prefix that will serve as shorthand for the given namespace URI in element names.
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 tha...
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.
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. :para...