text
stringlengths
81
112k
convert dict value if value is bool type, False -> "false" True -> "true" def filter_params(params): """ convert dict value if value is bool type, False -> "false" True -> "true" """ if params is not None: new_params = copy.deepcopy(params) new_params = dict((k, v) for k, v in new_params.items() if v is not None) for key, value in new_params.items(): if isinstance(value, bool): new_params[key] = "true" if value else "false" return new_params
error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: def _handler_response(self, response, data=None): """ error code response: { "request": "/statuses/home_timeline.json", "error_code": "20502", "error": "Need you follow uid." } :param response: :return: """ if response.status_code == 200: data = response.json() if isinstance(data, dict) and data.get("error_code"): raise WeiboAPIError(data.get("request"), data.get("error_code"), data.get("error")) else: return data else: raise WeiboRequestError( "Weibo API request error: status code: {code} url:{url} ->" " method:{method}: data={data}".format( code=response.status_code, url=response.url, method=response.request.method, data=data ) )
request weibo api :param suffix: str, :param params: dict, url query parameters :return: def get(self, suffix, params=None): """ request weibo api :param suffix: str, :param params: dict, url query parameters :return: """ url = self.base + suffix params = filter_params(params) response = self.session.get(url=url, params=params) return self._handler_response(response)
:return: def post(self, suffix, params=None, data=None, files=None): """ :return: """ url = self.base + suffix params = filter_params(params) response = self.session.post(url=url, params=params, data=data, files=files) return self._handler_response(response, data=data)
Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. *Note:* If allowed search keys are configured, only these are used. If no allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet, possibly causing a :exc:`~b2handle.handleexceptions.ReverseLookupException`. Example calls: * list_of_handles = search_handle('http://www.foo.com') * list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999) * list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999) :param URL: Optional. The URL to search for (reverse lookup). [This is NOT the URL of the search servlet!] :param prefix: Optional. The Handle prefix to which the search should be limited to. If unspecified, the method will search across all prefixes present at the server given to the constructor. :param key_value_pairs: Optional. Several search fields and values can be specified as key-value-pairs, e.g. CHECKSUM=123456, URL=www.foo.com :raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that cannot be used, or if something else goes wrong. :return: A list of all Handles (strings) that bear the given key with given value of given prefix or server. The list may be empty and may also contain more than one element. def search_handle(self, **args): ''' Search for handles containing the specified key with the specified value. The search terms are passed on to the reverse lookup servlet as-is. The servlet is supposed to be case-insensitive, but if it isn't, the wrong case will cause a :exc:`~b2handle.handleexceptions.ReverseLookupException`. *Note:* If allowed search keys are configured, only these are used. If no allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet, possibly causing a :exc:`~b2handle.handleexceptions.ReverseLookupException`. Example calls: * list_of_handles = search_handle('http://www.foo.com') * list_of_handles = search_handle('http://www.foo.com', CHECKSUM=99999) * list_of_handles = search_handle(URL='http://www.foo.com', CHECKSUM=99999) :param URL: Optional. The URL to search for (reverse lookup). [This is NOT the URL of the search servlet!] :param prefix: Optional. The Handle prefix to which the search should be limited to. If unspecified, the method will search across all prefixes present at the server given to the constructor. :param key_value_pairs: Optional. Several search fields and values can be specified as key-value-pairs, e.g. CHECKSUM=123456, URL=www.foo.com :raise: :exc:`~b2handle.handleexceptions.ReverseLookupException`: If a search field is specified that cannot be used, or if something else goes wrong. :return: A list of all Handles (strings) that bear the given key with given value of given prefix or server. The list may be empty and may also contain more than one element. ''' LOGGER.debug('search_handle...') if self.__has_search_access: return self.__search_handle(**args) else: LOGGER.error( 'Searching not possible. Reason: No access '+ 'to search system (endpoint: '+ str(self.__search_url)+').' ) return None
Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param fulltext_searchterms: Optional. Any term specified will be used as search term. Not implemented yet, so will be ignored. :param keyvalue_searchterms: Optional. Key-value pairs. Any key-value pair will be used to search for the value in the field "key". Wildcards accepted (refer to the documentation of the reverse lookup servlet for syntax.) :return: The query string, after the "?". If no valid search terms were specified, None is returned. def create_revlookup_query(self, *fulltext_searchterms, **keyvalue_searchterms): ''' Create the part of the solr request that comes after the question mark, e.g. ?URL=*dkrz*&CHECKSUM=*abc*. If allowed search keys are configured, only these are used. If no'allowed search keys are specified, all key-value pairs are passed on to the reverse lookup servlet. :param fulltext_searchterms: Optional. Any term specified will be used as search term. Not implemented yet, so will be ignored. :param keyvalue_searchterms: Optional. Key-value pairs. Any key-value pair will be used to search for the value in the field "key". Wildcards accepted (refer to the documentation of the reverse lookup servlet for syntax.) :return: The query string, after the "?". If no valid search terms were specified, None is returned. ''' LOGGER.debug('create_revlookup_query...') allowed_search_keys = self.__allowed_search_keys only_search_for_allowed_keys = False if len(allowed_search_keys) > 0: only_search_for_allowed_keys = True fulltext_searchterms_given = True fulltext_searchterms = b2handle.util.remove_value_none_from_list(fulltext_searchterms) if len(fulltext_searchterms) == 0: fulltext_searchterms_given = False if fulltext_searchterms_given: msg = 'Full-text search is not implemented yet.'+\ ' The provided searchterms '+str(fulltext_searchterms)+\ ' can not be used.' raise ReverseLookupException(msg=msg) keyvalue_searchterms_given = True keyvalue_searchterms = b2handle.util.remove_value_none_from_dict(keyvalue_searchterms) if len(keyvalue_searchterms) == 0: keyvalue_searchterms_given = False if not keyvalue_searchterms_given and not fulltext_searchterms_given: msg = 'No search terms have been specified. Please specify'+\ ' at least one key-value-pair.' raise ReverseLookupException(msg=msg) counter = 0 query = '?' for key, value in keyvalue_searchterms.items(): if only_search_for_allowed_keys and key not in allowed_search_keys: msg = 'Cannot search for key "'+key+'". Only searches '+\ 'for keys '+str(allowed_search_keys)+' are implemented.' raise ReverseLookupException(msg=msg) else: query = query+'&'+key+'='+value counter += 1 query = query.replace('?&', '?') LOGGER.debug('create_revlookup_query: query: '+query) if counter == 0: # unreachable? msg = 'No valid search terms have been specified.' raise ReverseLookupException(msg=msg) return query
Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password. def __set_revlookup_auth_string(self, username, password): ''' Creates and sets the authentication string for accessing the reverse lookup servlet. No return, the string is set as an attribute to the client instance. :param username: Username. :param password: Password. ''' auth = b2handle.utilhandle.create_authentication_string(username, password) self.__revlookup_auth_string = auth
Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_server_url": "https://url.to.your.handle.server", "username": "index:prefix/suffix", "password": "ZZZZZZZ", "prefix": "prefix_to_use_for_writing_handles", "handleowner": "username_to_own_handles" } Any additional key-value-pairs are stored in the instance as config. :raises: :exc:`~b2handle.handleexceptions.CredentialsFormatError` :raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError` :return: An instance. def load_from_JSON(json_filename): ''' Create a new instance of a PIDClientCredentials with information read from a local JSON file. :param json_filename: The path to the json credentials file. The json file should have the following format: .. code:: json { "handle_server_url": "https://url.to.your.handle.server", "username": "index:prefix/suffix", "password": "ZZZZZZZ", "prefix": "prefix_to_use_for_writing_handles", "handleowner": "username_to_own_handles" } Any additional key-value-pairs are stored in the instance as config. :raises: :exc:`~b2handle.handleexceptions.CredentialsFormatError` :raises: :exc:`~b2handle.handleexceptions.HandleSyntaxError` :return: An instance. ''' try: jsonfilecontent = json.loads(open(json_filename, 'r').read()) except ValueError as exc: raise CredentialsFormatError(msg="Invalid JSON syntax: "+str(exc)) instance = PIDClientCredentials(credentials_filename=json_filename,**jsonfilecontent) return instance
Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPython(**fixture(myapp, 'eggs.yaml')), migrations.RunPython(**fixture(anotherapp, ['sausage.json', 'walks.yaml'])) migrations.RunPython(**fixture(yap, ['foo.json'], reversible=False)) ] def fixture(app, fixtures, fixtures_dir='fixtures', raise_does_not_exist=False, reversible=True, models=[]): """ Load fixtures using a data migration. The migration will by default provide a rollback, deleting items by primary key. This is not always what you want ; you may set reversible=False to prevent rolling back. Usage: import myapp import anotherapp operations = [ migrations.RunPython(**fixture(myapp, 'eggs.yaml')), migrations.RunPython(**fixture(anotherapp, ['sausage.json', 'walks.yaml'])) migrations.RunPython(**fixture(yap, ['foo.json'], reversible=False)) ] """ fixture_path = os.path.join(app.__path__[0], fixtures_dir) if isinstance(fixtures, string_types): fixtures = [fixtures] def get_format(fixture): return os.path.splitext(fixture)[1][1:] def get_objects(): for fixture in fixtures: with open(os.path.join(fixture_path, fixture), 'rb') as f: objects = serializers.deserialize(get_format(fixture), f, ignorenonexistent=True) for obj in objects: yield obj def patch_apps(func): """ Patch the app registry. Note that this is necessary so that the Deserializer does not use the current version of the model, which may not necessarily be representative of the model the fixture was created for. """ @wraps(func) def inner(apps, schema_editor): try: # Firstly patch the serializers registry original_apps = django.core.serializers.python.apps django.core.serializers.python.apps = apps return func(apps, schema_editor) finally: # Ensure we always unpatch the serializers registry django.core.serializers.python.apps = original_apps return inner @patch_apps def load_fixture(apps, schema_editor): for obj in get_objects(): obj.save() @patch_apps def unload_fixture(apps, schema_editor): for obj in get_objects(): model = apps.get_model(app.__name__, obj.object.__class__.__name__) kwargs = dict() if 'id' in obj.object.__dict__: kwargs.update(id=obj.object.__dict__.get('id')) elif 'slug' in obj.object.__dict__: kwargs.update(slug=obj.object.__dict__.get('slug')) else: kwargs.update(**obj.object.__dict__) try: model.objects.get(**kwargs).delete() except model.DoesNotExist: if not raise_does_not_exist: raise FixtureObjectDoesNotExist(("Model %s instance with " "kwargs %s does not exist." % (model, kwargs))) kwargs = dict(code=load_fixture) if reversible: kwargs['reverse_code'] = unload_fixture return kwargs
Get all non-zero bits def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)]
Returns a hexadecimal string def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2)
Construct BitMap from hex string def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring)
Construct BitMap from string def fromstring(cls, bitstring): """ Construct BitMap from string """ nbits = len(bitstring) bm = cls(nbits) for i in xrange(nbits): if bitstring[-i-1] == '1': bm.set(i) elif bitstring[-i-1] != '0': raise Exception("Invalid bit string!") return bm
Get version information or return default if unable to do so. def get_versions(): """Get version information or return default if unable to do so.""" # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree"} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass _version_path = os.path.join(os.path.dirname(__file__), '_version') if os.path.exists(_version_path): with open(_version_path) as f: l = f.readline().strip() return { 'version': l, 'error': None, 'dirty': None, 'full-revisionid': l } return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version"}
Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string. def get_valid_https_verify(value): ''' Get a value that can be the boolean representation of a string or a boolean itself and returns It as a boolean. If this is not the case, It returns a string. :value: The HTTPS_verify input value. A string can be passed as a path to a CA_BUNDLE certificate :returns: True, False or a string. ''' http_verify_value = value bool_values = {'false': False, 'true': True} if isinstance(value, bool): http_verify_value = value elif (isinstance(value, str) or isinstance(value, unicode)) and value.lower() in bool_values.keys(): http_verify_value = bool_values[value.lower()] return http_verify_value
Setup filter (only called when filter is actually used). def setup(self): """Setup filter (only called when filter is actually used).""" super(RequireJSFilter, self).setup() excluded_files = [] for bundle in self.excluded_bundles: excluded_files.extend( map(lambda f: os.path.splitext(f)[0], bundle.contents) ) if excluded_files: self.argv.append( 'exclude={0}'.format(','.join(excluded_files)) )
Initialize filter just before it will be used. def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT')
Determine which option name to use. def rebase_opt(self): """Determine which option name to use.""" if not hasattr(self, '_rebase_opt'): # out = b"MAJOR.MINOR.REVISION" // b"3.4.19" or b"4.0.0" out, err = Popen( ['cleancss', '--version'], stdout=PIPE).communicate() ver = int(out[:out.index(b'.')]) self._rebase_opt = ['--root', self.root] if ver == 3 else [] return self._rebase_opt
Input filtering. def input(self, _in, out, **kw): """Input filtering.""" args = [self.binary or 'cleancss'] + self.rebase_opt if self.extra_args: args.extend(self.extra_args) self.subprocess(args, out, _in)
Wrap translation in Angular module. def output(self, _in, out, **kwargs): """Wrap translation in Angular module.""" out.write( 'angular.module("{0}", ["gettext"]).run(' '["gettextCatalog", function (gettextCatalog) {{'.format( self.catalog_name ) ) out.write(_in.read()) out.write('}]);')
Process individual translation file. def input(self, _in, out, **kwargs): """Process individual translation file.""" language_code = _re_language_code.search(_in.read()).group( 'language_code' ) _in.seek(0) # move at the begining after matching the language catalog = read_po(_in) out.write('gettextCatalog.setStrings("{0}", '.format(language_code)) out.write(json.dumps({ key: value.string for key, value in catalog._messages.items() if key and value.string })) out.write(');')
Check the combination username/password that is valid on the database. def get_user_and_check_auth(self, username, password): """Check the combination username/password that is valid on the database. """ constraint = sql.or_( models.USERS.c.name == username, models.USERS.c.email == username ) user = self.identity_from_db(models.USERS, constraint) if user is None: raise dci_exc.DCIException('User %s does not exists.' % username, status_code=401) return user, auth.check_passwords_equal(password, user.password)
Query the Github API to retrieve the needed infos. def retrieve_info(self): """Query the Github API to retrieve the needed infos.""" path = urlparse(self.url).path path = path.split('/')[1:] sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE) self.product = sanity_filter.match(path[0]).group(0) self.component = sanity_filter.match(path[1]).group(0) self.issue_id = int(path[3]) github_url = '%s/%s/%s/issues/%s' % (_URL_BASE, self.product, self.component, self.issue_id) result = requests.get(github_url) self.status_code = result.status_code if result.status_code == 200: result = result.json() self.title = result['title'] self.reporter = result['user']['login'] if result['assignee'] is not None: self.assignee = result['assignee']['login'] self.status = result['state'] self.created_at = result['created_at'] self.updated_at = result['updated_at'] self.closed_at = result['closed_at'] elif result.status_code == 404: self.title = 'private issue'
Cache the return value in the correct cache directory. Set 'method' to false for static methods. def disk_cache(cls, basename, function, *args, method=True, **kwargs): """ Cache the return value in the correct cache directory. Set 'method' to false for static methods. """ @utility.disk_cache(basename, cls.directory(), method=method) def wrapper(*args, **kwargs): return function(*args, **kwargs) return wrapper(*args, **kwargs)
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_directory(directory) return directory
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 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 __TABLE = models.JOBS query = sql.select([__TABLE.c.rconfiguration_id]). \ order_by(sql.desc(__TABLE.c.created_at)). \ where(sql.and_(__TABLE.c.topic_id == topic_id, __TABLE.c.remoteci_id == remoteci_id)). \ limit(1) rconfiguration_id = db_conn.execute(query).fetchone() if rconfiguration_id is not None: return str(rconfiguration_id[0]) else: return 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. 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_last_rconfiguration_id( topic_id, remoteci_id, db_conn=db_conn) _RCONFIGURATIONS = models.REMOTECIS_RCONFIGURATIONS _J_RCONFIGURATIONS = models.JOIN_REMOTECIS_RCONFIGURATIONS query = sql.select([_RCONFIGURATIONS]). \ select_from(_J_RCONFIGURATIONS. join(_RCONFIGURATIONS)). \ where(_J_RCONFIGURATIONS.c.remoteci_id == remoteci_id) query = query.where(sql.and_(_RCONFIGURATIONS.c.state != 'archived', _RCONFIGURATIONS.c.topic_id == topic_id)) query = query.order_by(sql.desc(_RCONFIGURATIONS.c.created_at)) query = query.order_by(sql.asc(_RCONFIGURATIONS.c.name)) all_rconfigurations = db_conn.execute(query).fetchall() if len(all_rconfigurations) > 0: for i in range(len(all_rconfigurations)): if str(all_rconfigurations[i]['id']) == last_rconfiguration_id: # if i==0, then indice -1 is the last element return all_rconfigurations[i - 1] return all_rconfigurations[0] else: return 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 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 """ handler_factories = self._registry.lookup(request) if len(handler_factories) != 1: raise ConfigurationException("There is no handler registered for this request") handler = handler_factories[0]() handler.handle(request)
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: handler = factory() handler.handle(request)
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 """ if self._producer is None: raise ConfigurationException("Command Processor requires a BrightsideProducer to post to a Broker") if self._message_mapper_registry is None: raise ConfigurationException("Command Processor requires a BrightsideMessage Mapper Registry to post to a Broker") message_mapper = self._message_mapper_registry.lookup(request) message = message_mapper(request) self._message_store.add(message) self._producer.send(message)
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 document. 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 document. """ for child in wrapped_node.children: if child.is_text and child.value.strip() == '': child.delete() else: cls.ignore_whitespace_text_nodes(child)
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 information, None is return for those tuple members. """ if '}' in name: ns_uri, name = name.split('}') ns_uri = ns_uri[1:] prefix = self.get_ns_prefix_for_uri(impl_node, ns_uri) elif ':' in name: prefix, name = name.split(':') ns_uri = self.get_ns_uri_for_prefix(impl_node, prefix) if ns_uri is None: raise exceptions.UnknownNamespaceException( "Prefix '%s' does not have a defined namespace URI" % prefix) else: prefix, ns_uri = None, None return prefix, name, ns_uri
: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 number of number of ancestors return the document's root element. :type count: integer >= 1 or None :param to_name: return the nearest ancestor element with the matching name, or the document's root element if there are no matching elements. This argument trumps the ``count`` argument. :type to_name: string or None 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 number of number of ancestors return the document's root element. :type count: integer >= 1 or None :param to_name: return the nearest ancestor element with the matching name, or the document's root element if there are no matching elements. This argument trumps the ``count`` argument. :type to_name: string or None """ elem = self._element up_count = 0 while True: # Don't go up beyond the document root if elem.is_root or elem.parent is None: break elem = elem.parent if to_name is None: up_count += 1 if up_count >= count: break else: if elem.name == to_name: break return Builder(elem)
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`. 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 = self._element.add_element(*args, **kwargs) return Builder(child_element)
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`. 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(*args, **kwargs) return self
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`. 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.add_instruction(target, data) return self
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`. 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, ns_uri) return self
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 - Organizational unit name CN - Common name emailAddress - E-mail address Returns: The certificate request in an X509Req object 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 arguments are: C - Country name ST - State or province name L - Locality name O - Organization name OU - Organizational unit name CN - Common name emailAddress - E-mail address Returns: The certificate request in an X509Req object """ req = crypto.X509Req() req.get_subject().C = "FR" req.get_subject().ST = "IDF" req.get_subject().L = "Paris" req.get_subject().O = "RedHat" # noqa req.get_subject().OU = "DCI" req.get_subject().CN = "DCI-remoteCI" req.set_pubkey(pkey) req.sign(pkey, digest) return req
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 row to look for :param get_id: if True, return only the ID :return: 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 row to look for :param get_id: if True, return only the ID :return: """ where_clause = table.c.id == id if name: where_clause = table.c.name == name if 'state' in table.columns: where_clause = sql.and_(table.c.state != 'archived', where_clause) query = sql.select([table]).where(where_clause) result = flask.g.db_conn.execute(query).fetchone() if result is None: raise dci_exc.DCIException('Resource "%s" not found.' % id, status_code=404) if get_id: return result.id return result
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( models.JOINS_TOPICS_TEAMS.join( models.TOPICS, sql.and_(models.JOINS_TOPICS_TEAMS.c.topic_id == models.TOPICS.c.id, # noqa models.TOPICS.c.state == 'active')) # noqa ).where( sql.or_(models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.teams_ids), # noqa models.JOINS_TOPICS_TEAMS.c.team_id.in_(user.child_teams_ids)))) # noqa rows = flask.g.db_conn.execute(query).fetchall() return [str(row[0]) for row in rows]
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): raise dci_exc.Unauthorized()
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': 'name2', 'b' : {'id': 'id2', 'name': 'name2'}, {'id' : 'id3', 'name': 'name3', 'b' : {'id': 'id4', 'name': 'name4'} ] """ result_rows = [] for row in rows: row = dict(row) result_row = {} prefixes_to_remove = [] for field in row: if field.startswith('next_topic'): prefix = 'next_topic' suffix = field[11:] if suffix == 'id_1': suffix = 'id' else: prefix, suffix = field.split('_', 1) if suffix == 'id' and row[field] is None: prefixes_to_remove.append(prefix) if prefix not in result_row: result_row[prefix] = {suffix: row[field]} else: result_row[prefix].update({suffix: row[field]}) # remove field with id == null for prefix_to_remove in prefixes_to_remove: result_row.pop(prefix_to_remove) root_table_fields = result_row.pop(root_table_name) result_row.update(root_table_fields) result_rows.append(result_row) return result_rows
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' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', 'name' : 'name4} } ] Here there is two elements which correspond to one rows because of the embed field 'b'. So we should transform it to: [{'id' : 'id1', 'name' : 'name1, 'b' : [{'id': 'id2, 'name': 'name2'}, {'id' : 'id4', 'name' : 'name4}] } ] This is the purpose of this function. 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' : 'id1', 'name' : 'name1, 'b' : {'id' : 'id4', 'name' : 'name4} } ] Here there is two elements which correspond to one rows because of the embed field 'b'. So we should transform it to: [{'id' : 'id1', 'name' : 'name1, 'b' : [{'id': 'id2, 'name': 'name2'}, {'id' : 'id4', 'name' : 'name4}] } ] This is the purpose of this function. """ def _uniqify_list(list_of_dicts): # list() for py34 result = [] set_ids = set() for v in list_of_dicts: if v['id'] in set_ids: continue set_ids.add(v['id']) result.append(v) return result row_ids_to_embed_values = {} for row in rows: # for each row, associate rows's id -> {all embeds values} if row['id'] not in row_ids_to_embed_values: row_ids_to_embed_values[row['id']] = {} # add embeds values to the current row for embd in list_embeds: if embd not in row: continue if embd not in row_ids_to_embed_values[row['id']]: # create a list or a dict depending on embed_many if embed_many[embd]: row_ids_to_embed_values[row['id']][embd] = [row[embd]] else: row_ids_to_embed_values[row['id']][embd] = row[embd] else: if embed_many[embd]: row_ids_to_embed_values[row['id']][embd].append(row[embd]) # uniqify each embed list for embd in list_embeds: if embd in row_ids_to_embed_values[row['id']]: embed_values = row_ids_to_embed_values[row['id']][embd] if isinstance(embed_values, list): row_ids_to_embed_values[row['id']][embd] = _uniqify_list(embed_values) # noqa else: row_ids_to_embed_values[row['id']][embd] = {} if embed_many[embd]: row_ids_to_embed_values[row['id']][embd] = [] # last loop over the initial rows in order to keep the ordering result = [] # if row id in seen set then it means the row has been completely processed seen = set() for row in rows: if row['id'] in seen: continue seen.add(row['id']) new_row = {} # adds level 1 fields for field in row: if field not in list_embeds: new_row[field] = row[field] # adds all level 2 fields # list() for py34 row_ids_to_embed_values_keys = list(row_ids_to_embed_values[new_row['id']].keys()) # noqa row_ids_to_embed_values_keys.sort() # adds the nested fields if there is somes for embd in list_embeds: if embd in row_ids_to_embed_values_keys: if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row[embd] = row_ids_to_embed_values[new_row['id']][embd] # noqa else: new_row_embd_value = {} if embed_many[embd]: new_row_embd_value = [] if '.' in embd: prefix, suffix = embd.split('.', 1) new_row[prefix][suffix] = new_row_embd_value else: new_row[embd] = new_row_embd_value # row is complete ! result.append(new_row) return result
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. 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 = utils.gen_etag() values = { 'id': utils.gen_uuid(), 'created_at': now, 'updated_at': now, 'etag': etag } return values
: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) if fetchall: return flask.g.db_conn.execute(query).fetchall() elif fetchone: return flask.g.db_conn.execute(query).fetchone()
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, 'fullname': identity.fullname, 'email': identity.email, 'timezone': identity.timezone, 'teams': _encode_dict(identity.teams) } } ), 200, headers={'ETag': identity.etag}, content_type='application/json' )
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 been run with. if table.name == 'jobs': JJI = models.JOIN_JOBS_ISSUES JJC = models.JOIN_JOBS_COMPONENTS JCI = models.JOIN_COMPONENTS_ISSUES # Get all the issues attach to all the components attach to a job j1 = sql.join( _TABLE, sql.join( JCI, JJC, sql.and_( JCI.c.component_id == JJC.c.component_id, JJC.c.job_id == resource_id, ), ), _TABLE.c.id == JCI.c.issue_id, ) query = sql.select([_TABLE]).select_from(j1) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] # Get all the issues attach to a job j2 = sql.join( _TABLE, JJI, sql.and_( _TABLE.c.id == JJI.c.issue_id, JJI.c.job_id == resource_id ) ) query2 = sql.select([_TABLE]).select_from(j2) rows2 = flask.g.db_conn.execute(query2) rows += [dict(row) for row in rows2] # When retrieving the issues for a component, we only retrieve the # issues attached to the specified component. else: JCI = models.JOIN_COMPONENTS_ISSUES query = (sql.select([_TABLE]) .select_from(JCI.join(_TABLE)) .where(JCI.c.component_id == resource_id)) rows = flask.g.db_conn.execute(query) rows = [dict(row) for row in rows] for row in rows: if row['tracker'] == 'github': l_tracker = github.Github(row['url']) elif row['tracker'] == 'bugzilla': l_tracker = bugzilla.Bugzilla(row['url']) row.update(l_tracker.dump()) return flask.jsonify({'issues': rows, '_meta': {'count': len(rows)}})
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, join_table.c.issue_id == issue_id) else: join_table = models.JOIN_COMPONENTS_ISSUES where_clause = sql.and_(join_table.c.component_id == resource_id, join_table.c.issue_id == issue_id) query = join_table.delete().where(where_clause) result = flask.g.db_conn.execute(query) if not result.rowcount: raise dci_exc.DCIConflict('%s_issues' % table.name, issue_id) return flask.Response(None, 204, content_type='application/json')
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': join_table = models.JOIN_JOBS_ISSUES else: join_table = models.JOIN_COMPONENTS_ISSUES key = '%s_id' % table.name[0:-1] query = join_table.insert().values({ 'user_id': user_id, 'issue_id': issue['id'], key: resource_id }) try: flask.g.db_conn.execute(query) except sa_exc.IntegrityError: raise dci_exc.DCICreationConflict(join_table.name, '%s, issue_id' % key) result = json.dumps({'issue': dict(issue)}) return flask.Response(result, 201, content_type='application/json')
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 job['team_id'] not in user.child_teams_ids): raise dci_exc.Unauthorized() query = v1_utils.QueryBuilder(_TABLE, args, _JS_COLUMNS) query.add_extra_condition(_TABLE.c.job_id == job_id) # get the number of rows for the '_meta' section 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 flask.jsonify({'jobstates': rows, '_meta': {'count': nb_rows}})
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 (201, 409): print('Keycloak client dci created successfully.') else: raise Exception( 'Error while creating Keycloak client dci:\nstatus code %s\n' 'error: %s' % (r.status_code, r.content) )
Create the a dci user. username=dci, password=dci, email=dci@distributed-ci.io 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': [{'type': 'password', 'value': 'dci'}]} r = requests.post('http://keycloak:8080/auth/admin/realms/dci-test/users', data=json.dumps(user_data), headers=get_auth_headers(access_token)) if r.status_code in (201, 409): print('Keycloak user dci created successfully.') else: raise Exception('Error while creating user dci:\nstatus code %s\n' 'error: %s' % (r.status_code, r.content))
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. : str | `None` """ self.base = none_or(base, str) """ TODO: ??? : str | `None` """ self.generator = none_or(generator, str) """ TODO: ??? : str | `None` """ self.case = none_or(case, str) """ TODO: ??? : str | `None` """ self.namespaces = none_or(namespaces, list) """ A list of :class:`mwtypes.Namespace` | `None` """
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 return serialized for k, v in params.items(): if isinstance(v, bool): params[k] = str(v).lower()
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.accountemail: headers.update({'Account-Email': self.accountemail}) # Method selection handling if method.upper() == 'GET': response = requests.get(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'POST': response = requests.post(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'PUT': response = requests.put(self.url + url, data=parameters, auth=(self.username, self.password), headers=headers) elif method.upper() == 'DELETE': response = requests.delete(self.url + url, params=parameters, auth=(self.username, self.password), headers=headers) else: raise Exception("Invalid method in pingdom request") # Store pingdom api limits self.shortlimit = response.headers.get( 'Req-Limit-Short', self.shortlimit) self.longlimit = response.headers.get( 'Req-Limit-Long', self.longlimit) # Verify OK response if response.status_code != 200: sys.stderr.write('ERROR from %s: %d' % (response.url, response.status_code)) sys.stderr.write('Returned data: %s\n' % response.json()) response.raise_for_status() return response
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 Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } 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 Default: None * to -- Only include actions generated prior to this timestamp. Format is UNIX time. Type: Integer Default: None * limit -- Limits the number of returned results to the specified quantity. Type: Integer (max 300) Default: 100 * offset -- Offset for listing. Type: Integer Default: 0 * checkids -- Comma-separated list of check identifiers. Limit results to actions generated from these checks. Type: String Default: All * contactids -- Comma-separated list of contact identifiers. Limit results to actions sent to these contacts. Type: String Default: All * status -- Comma-separated list of statuses. Limit results to actions with these statuses. Type: String ['sent', 'delivered', 'error', 'not_delivered', 'no_credits'] Default: All * via -- Comma-separated list of via mediums. Limit results to actions with these mediums. Type: String ['email', 'sms', 'twitter', 'iphone', 'android'] Default: All Returned structure: { 'alerts' : [ { 'contactname' : <String> Name of alerted contact 'contactid' : <String> Identifier of alerted contact 'checkid' : <String> Identifier of check 'time' : <Integer> Time of alert generation. Format UNIX time 'via' : <String> Alert medium ['email', 'sms', 'twitter', 'iphone', 'android'] 'status' : <String> Alert status ['sent', 'delivered', 'error', 'notdelivered', 'nocredits'] 'messageshort': <String> Short description of message 'messagefull' : <String> Full message body 'sentto' : <String> Target address, phone number, etc 'charged' : <Boolean> True if your account was charged for this message }, ... ] } """ # Warn user about unhandled parameters for key in parameters: if key not in ['from', 'to', 'limit', 'offset', 'checkids', 'contactids', 'status', 'via']: sys.stderr.write('%s not a valid argument for actions()\n' % key) response = self.request('GET', 'actions', parameters) return response.json()['actions']
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 -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None 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 -- Offset for listing (requires limit.) Type: Integer Default: 0 * tags -- Filter listing by tag/s Type: String Default: None """ # Warn user about unhandled parameters for key in parameters: if key not in ['limit', 'offset', 'tags']: sys.stderr.write('%s not a valid argument for getChecks()\n' % key) response = self.request('GET', 'checks', parameters) return [PingdomCheck(self, x) for x in response.json()['checks']]
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 Parameters: * limit -- Limits the number of returned probes to the specified quantity Type: Integer * offset -- Offset for listing (requires limit). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] 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). Type: Integer Default: 0 * onlyactive -- Return only active probes Type: Boolean Default: False * includedeleted -- Include old probes that are no longer in use Type: Boolean Default: False Returned structure: [ { 'id' : <Integer> Unique probe id 'country' : <String> Country 'city' : <String> City 'name' : <String> Name 'active' : <Boolean> True if probe is active 'hostname' : <String> DNS name 'ip' : <String> IP address 'countryiso': <String> Country ISO code }, ... ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset', 'onlyactive', 'includedeleted']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of probes()\n') return self.request("GET", "probes", kwargs).json()['probes']
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' : <Integer> Probe identifier 'probedescription' : <String> Probe description } 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' : <Integer> Probe identifier 'probedescription' : <String> Probe description } """ response = self.request('GET', 'traceroute', {'host': host, 'probeid': probeid}) return response.json()['traceroute']
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 listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] 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 listing (requires limit.) Type: Integer Default: 0 Returned structure: [ 'id' : <Integer> Contact identifier 'name' : <String> Contact name 'email' : <String> Contact email 'cellphone' : <String> Contact telephone 'countryiso' : <String> Cellphone country ISO code 'defaultsmsprovider' : <String> Default SMS provider 'directtwitter' : <Boolean> Send Tweets as direct messages 'twitteruser' : <String> Twitter username 'paused' : <Boolean> True if contact is pasued 'iphonetokens' : <String list> iPhone tokens 'androidtokens' : <String list> android tokens ] """ # Warn user about unhandled parameters for key in kwargs: if key not in ['limit', 'offset']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of getContacts()\n') return [PingdomContact(self, x) for x in self.request("GET", "notification_contacts", kwargs).json()['contacts']]
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 -- 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 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 -- 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']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newContact()\n') kwargs['name'] = name contactinfo = self.request("POST", "notification_contacts", kwargs).json()['contact'] return PingdomContact(self, contactinfo)
Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message 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, 'paused': paused}) return response.json()['message']
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 Returns status message for operation Optional parameters: * checkid -- Check identifier. If omitted, this will be an overview report Type: Integer * frequency -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String 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 -- Report frequency Type: String ['monthly', 'weekly', 'daily'] * contactids -- Comma separated list of receiving contact identifiers Type: String * additionalemails -- Comma separated list of additional receiving emails Type: String """ # Warn user about unhandled parameters for key in kwargs: if key not in ['checkid', 'frequency', 'contactids', 'additionalemails']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newEmailReport()\n') parameters = {'name': name} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.email', parameters).json()['message']
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). Returns status message for operation Optional parameters: * auto -- Automatic period (If false, requires: fromyear, frommonth, fromday, toyear, tomonth, today) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer 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) Type: Boolean * type -- Banner type Type: String ['uptime', 'response'] * fromyear -- Period start: year Type: Integer * frommonth -- Period start: month Type: Integer * fromday -- Period start: day Type: Integer * toyear -- Period end: year Type: Integer * tomonth -- Period end: month Type: Integer * today -- Period end: day Type: Integer """ # Warn user about unhandled parameters for key in kwargs: if key not in ['auto', 'type', 'fromyear', 'frommonth', 'fromday', 'toyear', 'tomonth', 'today', 'sharedtype']: sys.stderr.write("'%s'" % key + ' is not a valid argument ' + 'of newSharedReport()\n') parameters = {'checkid': checkid, 'sharedtype': 'banner'} for key, value in kwargs.iteritems(): parameters[key] = value return self.request('POST', 'reports.shared', parameters).json()['message']
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 encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data. 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. :param masterkey: a 32 bytes key in bytes. :param bool_encry: if bool_encry is True, data is encrypted. Else, it will be decrypted. :param assoc_data: Additional data added to GCM authentication. :return: if bool_encry is True, corresponding nonce + encrypted data. Else, the decrypted data. """ engine1 = botan.cipher(algo="Serpent/GCM", encrypt=bool_encry) engine2 = botan.cipher(algo="AES-256/GCM", encrypt=bool_encry) engine3 = botan.cipher(algo="Twofish/GCM", encrypt=bool_encry) hash1 = botan.hash_function(algo="SHA-256") hash1.update(masterkey) hashed1 = hash1.final() hash2 = botan.hash_function(algo="SHA-256") hash2.update(hashed1) hashed2 = hash2.final() engine1.set_key(key=masterkey) engine1.set_assoc_data(assoc_data) engine2.set_key(key=hashed1) engine2.set_assoc_data(assoc_data) engine3.set_key(key=hashed2) engine3.set_assoc_data(assoc_data) if bool_encry is True: nonce1 = generate_nonce_timestamp() nonce2 = generate_nonce_timestamp() nonce3 = generate_nonce_timestamp() engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) cipher1 = engine1.finish(data) cipher2 = engine2.finish(cipher1) cipher3 = engine3.finish(cipher2) return nonce1 + nonce2 + nonce3 + cipher3 else: nonce1 = data[:__nonce_length__] nonce2 = data[__nonce_length__:__nonce_length__ * 2] nonce3 = data[__nonce_length__ * 2:__nonce_length__ * 3] encrypteddata = data[__nonce_length__ * 3:] engine1.start(nonce=nonce1) engine2.start(nonce=nonce2) engine3.start(nonce=nonce3) decrypteddata1 = engine3.finish(encrypteddata) if decrypteddata1 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata2 = engine2.finish(decrypteddata1) if decrypteddata2 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") decrypteddata3 = engine1.finish(decrypteddata2) if decrypteddata3 == b"": raise Exception("Integrity failure: Invalid passphrase or corrupted data") else: return decrypteddata3
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 dispatch to :return: """ key = request_class.__name__ is_command = request_class.is_command() is_event = request_class.is_event() is_present = key in self._registry if is_command and is_present: raise ConfigurationException("A handler for this request has already been registered") elif is_event and is_present: self._registry[key].append(handler_factory) elif is_command or is_event: self._registry[key] = [handler_factory]
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__.__name__ if key not in self._registry: if request.is_command(): raise ConfigurationException("There is no handler registered for this request") elif request.is_event(): return [] # type: Callable[[] Handler] return self._registry[key]
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 """ key = request_class.__name__ if key not in self._registry: self._registry[key] = mapper_func else: raise ConfigurationException("There is already a message mapper defined for this key; there can be only one")
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_class: :return: """ key = request_class.__class__.__name__ if key not in self._registry: raise ConfigurationException("There is no message mapper associated with this key; we require a mapper") else: return self._registry[key]
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 function generator. It returns a validation function to check that `instance_of(x, ref_type)`. :param args: :return: 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 * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `instance_of(x, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode value, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if isinstance(value, ref_type): return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type) else: # ref_type is a set match = False # test against each of the provided types for ref in ref_type: if isinstance(value, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=value, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): # ref_type is a single type def instance_of_ref(x): if isinstance(x, ref_type): return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type) else: # ref_type is a set def instance_of_ref(x): match = False # test against each of the provided types for ref in ref_type: if isinstance(x, ref): match = True break if match: return True else: raise HasWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be an instance of any of {ref_type}') instance_of_ref.__name__ = 'instance_of_{}'.format(ref_type) return instance_of_ref else: raise TypeError('instance_of expected 2 (normal) or 1 (function generator) arguments, got ' + str(len(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 * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `subclass_of(c, ref_type)`. :param args: :return: 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 * providing a single argument (ref_type), this is a function generator. It returns a validation function to check that `subclass_of(c, ref_type)`. :param args: :return: """ if len(args) == 2: # Standard mode typ, ref_type = args if not isinstance(ref_type, set): # ref_type is a single type if issubclass(typ, ref_type): return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type) else: # ref_type is a set match = False # test against each of the provided types for ref in ref_type: if issubclass(typ, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=typ, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') elif len(args) == 1: # Function generator mode ref_type = args[0] if not isinstance(ref_type, set): def subclass_of_ref(x): if issubclass(x, ref_type): return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type) else: # ref_type is a set def subclass_of_ref(x): match = False # test against each of the provided types for ref in ref_type: if issubclass(x, ref): match = True break if match: return True else: raise IsWrongType(wrong_value=x, ref_type=ref_type, help_msg='Value should be a subclass of any of {ref_type}') subclass_of_ref.__name__ = 'subclass_of_{}'.format(ref_type) return subclass_of_ref else: raise TypeError('subclass_of expected 2 (normal) or 1 (function generator) arguments, got ' + str(len(args)))
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.pickle'. """ directory = os.path.expanduser(directory) ensure_directory(directory) def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): key = (tuple(args), tuple(kwargs.items())) # Don't use self or cls for the invalidation hash. if method and key: key = key[1:] filename = '{}-{}.pickle'.format(basename, hash(key)) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): with open(filepath, 'rb') as handle: return pickle.load(handle) result = func(*args, **kwargs) with open(filepath, 'wb') as handle: pickle.dump(result, handle) return result return wrapped return wrapper
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 = os.path.split(url) directory = os.path.expanduser(directory) ensure_directory(directory) filepath = os.path.join(directory, filename) if os.path.isfile(filepath): return filepath print('Download', filepath) with urlopen(url) as response, open(filepath, 'wb') as file_: shutil.copyfileobj(response, file_) return filepath
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. valid8 supports the following expressions for 'validation functions' * <ValidationFunc> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :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_`. 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 auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return: 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 '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. valid8 supports the following expressions for 'validation functions' * <ValidationFunc> * List[<ValidationFunc>(s)]. The list must not be empty. <ValidationFunc> may either be * a callable or a mini-lambda expression (instance of LambdaExpression - in which case it is automatically 'closed'). * a Tuple[callable or mini-lambda expression ; failure_type]. Where failure type should be a subclass of valid8.Failure. In which case the tuple will be replaced with a _failure_raiser(callable, failure_type) When the contents provided does not match the above, this function raises a ValueError. Otherwise it produces a list of callables, that will typically be turned into a `and_` in the nominal case except if this is called inside `or_` or `xor_`. :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_`. 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 auto_and_wrapper: if True (default), this function returns a single callable that is a and_() of all functions. Otherwise a list is returned. :return: """ # handle the case where validation_func is not yet a list or is empty or none if validation_func is None: raise ValueError('mandatory validation_func is None') elif not isinstance(validation_func, list): # so not use list() because we do not want to convert tuples here. validation_func = [validation_func] elif len(validation_func) == 0: raise ValueError('provided validation_func list is empty') # now validation_func is a non-empty list final_list = [] for v in validation_func: # special case of a LambdaExpression: automatically convert to a function # note: we have to do it before anything else (such as .index) otherwise we may get failures v = as_function(v) if isinstance(v, tuple): # convert all the tuples to failure raisers if len(v) == 2: if isinstance(v[1], str): final_list.append(_failure_raiser(v[0], help_msg=v[1])) elif isinstance(v[1], type) and issubclass(v[1], WrappingFailure): final_list.append(_failure_raiser(v[0], failure_type=v[1])) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) elif callable(v): # use the validator directly final_list.append(v) elif isinstance(v, list): # a list is an implicit and_, make it explicit final_list.append(and_(*v)) else: raise TypeError('base validation function(s) not compliant with the allowed syntax. Base validation' ' function(s) can be {}. Found [{}].'.format(supported_syntax, str(v))) # return what is required: if auto_and_wrapper: # a single callable doing the 'and' return and_(*final_list) else: # or the list (typically for use inside or_(), xor_()...) return final_list
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_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :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 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_` is performed if you provide a list of validators to any of the entry points (`validate`, `validation`/`validator`, `@validate_arg`, `@validate_out`, `@validate_field` ...) :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: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case: no wrapper else: def and_v_(x): for validator in validation_func: try: res = validator(x) except Exception as e: # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x, cause=e) if not result_is_success(res): # one validator was unhappy > raise raise AtLeastOneFailed(validation_func, x) return True and_v_.__name__ = 'and({})'.format(get_callable_names(validation_func)) return and_v_
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. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. 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 catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: 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 `DidNotFail` failure. By default, exceptions of types other than `Failure` are not caught and therefore fail the validation (`catch_all=False`). To change this behaviour you can turn the `catch_all` parameter to `True`, in which case all exceptions will be caught instead of just `Failure`s. Note that you may use `not_all(<validation_functions_list>)` as a shortcut for `not_(and_(<validation_functions_list>))` :param validation_func: the base validation function. 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 catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ def not_v_(x): try: res = validation_func(x) if not result_is_success(res): # inverse the result return True except Failure: return True # caught failure: always return True except Exception as e: if not catch_all: raise e else: return True # caught exception in 'catch_all' mode: return True # if we're here that's a failure raise DidNotFail(wrapped_func=validation_func, wrong_value=x, validation_outcome=res) not_v_.__name__ = 'not({})'.format(get_callable_name(validation_func)) return not_v_
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. :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 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, together with details about all validation results. :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: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validator case else: def or_v_(x): for validator in validation_func: # noinspection PyBroadException try: res = validator(x) if result_is_success(res): # we can return : one validator was happy return True except Exception: # catch all silently pass # no validator accepted: gather details and raise raise AllValidatorsFailed(validation_func, x) or_v_.__name__ = 'or({})'.format(get_callable_names(validation_func)) return or_v_
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. :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 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 `AllValidatorsFailed` will be raised, together with details about the various validation results. :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: """ validation_func = _process_validation_function_s(list(validation_func), auto_and_wrapper=False) if len(validation_func) == 1: return validation_func[0] # simplification for single validation function case else: def xor_v_(x): ok_validators = [] for val_func in validation_func: # noinspection PyBroadException try: res = val_func(x) if result_is_success(res): ok_validators.append(val_func) except Exception: pass # return if were happy or not if len(ok_validators) == 1: # one unique validation function happy: success return True elif len(ok_validators) > 1: # several validation_func happy : fail raise XorTooManySuccess(validation_func, x) else: # no validation function happy, fail raise AllValidatorsFailed(validation_func, x) xor_v_.__name__ = 'xor({})'.format(get_callable_names(validation_func)) return xor_v_
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_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 catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: 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_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 catch_all: an optional boolean flag. By default, only Failure are silently caught and turned into a 'ok' result. Turning this flag to True will assume that all exceptions should be caught and turned to a 'ok' result :return: """ catch_all = pop_kwargs(kwargs, [('catch_all', False)]) # in case this is a list, create a 'and_' around it (otherwise and_ will return the validation function without # wrapping it) main_validator = and_(*validation_func) return not_(main_validator, catch_all=catch_all)
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 raising an exception) :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 failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return: 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` decorators. It transforms the provided `<function>` into a failure raiser, raising a subclass of `Failure` in case of failure (either not returning `True` or raising an exception) :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 failure_type: a subclass of `WrappingFailure` that should be raised in case of failure :param help_msg: a string help message for the raised `WrappingFailure`. Optional (default = WrappingFailure with no help message). :param kw_context_args :return: """ failure_type, help_msg = pop_kwargs(kwargs, [('failure_type', None), ('help_msg', None)], allow_others=True) # the rest of keyword arguments is used as context. kw_context_args = kwargs main_func = _process_validation_function_s(list(validation_func)) return _failure_raiser(main_func, failure_type=failure_type, help_msg=help_msg, **kw_context_args)
Internal utility method to extract optional arguments from kwargs. :param kwargs: :param names_with_defaults: :param allow_others: if False (default) then an error will be raised if kwargs still contains something at the end. :return: 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) then an error will be raised if kwargs still contains something at the end. :return: """ all_arguments = [] for name, default_ in names_with_defaults: try: val = kwargs.pop(name) except KeyError: val = default_ all_arguments.append(val) if not allow_others and len(kwargs) > 0: raise ValueError("Unsupported arguments: %s" % kwargs) if len(names_with_defaults) == 1: return all_arguments[0] else: return all_arguments
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.failures.items(): name = get_callable_name(validator) if isinstance(failure, Exception): if isinstance(failure, WrappingFailure) or isinstance(failure, CompositionFailure): need_to_print_value = False failures_for_print[name] = '{exc_type}: {msg}'.format(exc_type=type(failure).__name__, msg=str(failure)) else: failures_for_print[name] = str(failure) if need_to_print_value: value_str = ' for value [{val}]'.format(val=self.wrong_value) else: value_str = '' # OrderedDict does not pretty print... key_values_str = [repr(key) + ': ' + repr(val) for key, val in failures_for_print.items()] failures_for_print_str = '{' + ', '.join(key_values_str) + '}' # Note: we do note cite the value in the message since it is most probably available in inner messages [{val}] msg = '{what}{possibly_value}. Successes: {success} / Failures: {fails}' \ ''.format(what=self.get_what(), possibly_value=value_str, success=self.successes, fails=failures_for_print_str) return msg
Utility method to play all the provided validators on the provided value and output the :param validators: :param value: :return: 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 in validators: name = get_callable_name(validator) try: res = validator(value) if result_is_success(res): successes.append(name) else: failures[validator] = res except Exception as exc: failures[validator] = exc return successes, failures
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 is srp. :return: a string with "successfully encrypted" or error. """ try: if algo == "srp": header = b"Cryptoshop srp " + b_version crypto_algo = "Serpent/GCM" if algo == "aes": header = b"Cryptoshop aes " + b_version crypto_algo = "AES-256/GCM" if algo == "twf": header = b"Cryptoshop twf " + b_version crypto_algo = "Twofish/GCM" if algo != "srp" and algo != "aes" and algo != "twf": return "No valid algo. Use 'srp' 'aes' or 'twf'" outname = filename + ".cryptoshop" internal_key = botan.rng().get(internal_key_length) # Passphrase derivation... salt = botan.rng().get(__salt_size__) masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Encrypt internal key... encrypted_key = encry_decry_cascade(data=internal_key, masterkey=masterkey, bool_encry=True, assoc_data=header) with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't encrypt empty file.") with open(str(outname), 'wb') as filestreamout: filestreamout.write(header) filestreamout.write(salt) filestreamout.write(encrypted_key) finished = False # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(file_size // __chunk_size__)) while not finished: chunk = filestream.read(__chunk_size__) if len(chunk) == 0 or len(chunk) % __chunk_size__ != 0: finished = True # An encrypted-chunk output is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = encry_decry_chunk(chunk=chunk, key=internal_key, bool_encry=True, algo=crypto_algo, assoc_data=header) filestreamout.write(encryptedchunk) bar.update(1) return "successfully encrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
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" or error. """ try: outname = os.path.splitext(filename)[0].split("_")[-1] # create a string file name without extension. with open(filename, 'rb') as filestream: file_size = os.stat(filename).st_size if file_size == 0: raise Exception("Error: You can't decrypt empty file.") fileheader = filestream.read(header_length) if fileheader == b"Cryptoshop srp " + b_version: decrypt_algo = "Serpent/GCM" if fileheader == b"Cryptoshop aes " + b_version: decrypt_algo = "AES-256/GCM" if fileheader == b"Cryptoshop twf " + b_version: decrypt_algo = "Twofish/GCM" if fileheader != b"Cryptoshop srp " + b_version and fileheader != b"Cryptoshop aes " + b_version and fileheader != b"Cryptoshop twf " + b_version: raise Exception("Integrity failure: Bad header") salt = filestream.read(__salt_size__) encrypted_key = filestream.read(encrypted_key_length) # Derive the passphrase... masterkey = calc_derivation(passphrase=passphrase, salt=salt) # Decrypt internal key... try: internal_key = encry_decry_cascade(data=encrypted_key, masterkey=masterkey, bool_encry=False, assoc_data=fileheader) except Exception as e: return e with open(str(outname), 'wb') as filestreamout: files_size = os.stat(filename).st_size # the maximum of the progress bar is the total chunk to process. It's files_size // chunk_size bar = tqdm(range(files_size // __chunk_size__)) while True: # Don't forget... an encrypted chunk is nonce, gcmtag, and cipher-chunk concatenation. encryptedchunk = filestream.read(__nonce_length__ + __gcmtag_length__ + __chunk_size__) if len(encryptedchunk) == 0: break # Chunk decryption. try: original = encry_decry_chunk(chunk=encryptedchunk, key=internal_key, algo=decrypt_algo, bool_encry=False, assoc_data=fileheader) except Exception as e: return e else: filestreamout.write(original) bar.update(1) return "successfully decrypted" except IOError: exit("Error: file \"" + filename + "\" was not found.")
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()] yield from cls._split(chunk) tag = match.group(0) yield tag sentence = sentence[(len(chunk) + len(tag)):]
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 path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ... 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()` function that takes two arguments -- a :class:`mwxml.Dump` and the path the dump was loaded from. Anything that this function ``yield``s will be `yielded` in turn from the :func:`mwxml.map` function. :Parameters: paths : `iterable` ( `str` | `file` ) a list of paths to dump files to process process : `func` A function that takes a :class:`~mwxml.iteration.dump.Dump` and the path the dump was loaded from and yields threads : int the number of individual processing threads to spool up :Example: >>> import mwxml >>> files = ["examples/dump.xml", "examples/dump2.xml"] >>> >>> def page_info(dump, path): ... for page in dump: ... yield page.id, page.namespace, page.title ... >>> for id, namespace, title in mwxml.map(page_info, files): ... print(id, namespace, title) ... """ paths = [mwtypes.files.normalize_path(path) for path in paths] def process_path(path): dump = Dump.from_file(mwtypes.files.reader(path)) yield from process(dump, path) yield from para.map(process_path, paths, mappers=threads)
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': self.component, 'created_at': self.created_at, 'updated_at': self.updated_at, 'closed_at': self.closed_at, 'status_code': self.status_code }
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: `func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)` :param func: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return: 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 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: `func_to_apply(cur_att_value, func_to_apply_paramers_dict[att], func, att_name)` :param func: :param cur_args: :param cur_kwargs: :param sig: :param func_to_apply: :param func_to_apply_params_dict: :return: """ # match the received arguments with the signature to know who is who bound_values = sig.bind(*cur_args, **cur_kwargs) # add the default values in here to get a full list apply_defaults(bound_values) for att_name, att_value in bound_values.arguments.items(): if att_name in func_to_apply_params_dict.keys(): # value = a normal value, or cur_kwargs as a whole func_to_apply(att_value, func_to_apply_params_dict[att_name], func, att_name)
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'] == 'REMOTECI'
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'