code stringlengths 1 18.2k |
|---|
continue # Subset by before and after date_tag = leaf.find('.//{%s}date[@type="modified"]' % INV_NS) if date_tag is not None: try: dt = parse(date_tag.text) except ValueError: logger.error("Skipping dataset.Wrong date string %s " % date_tag.text) continue else: dt = dt.replace(tzinfo=pytz.utc) if self.after and dt < se... |
if gid is not None and any([x.match(gid) for x in self.select]): logger.debug("Processing %s" % gid) yield "%s?dataset=%s" % (url, gid) else: logger.info("Ignoring dataset based on 'selects'. ID: %s" % gid) continue else: logger.debug("Processing %s" % gid) yield "%s?dataset=%s" % (url, gid) |
def _compile_references(self, url, tree): ''' Returns a list of catalog reference URLs for the current catalog :param str url: URL for the current catalog :param lxml.etree.Eleemnt tree: Current XML Tree ''' references = [] for ref in tree.findall('.//{%s}catalogRef' % INV_NS): # Check skips title = ref.get("{%s}title"... |
references.append(construct_url(url, ref.get("{%s}href" % XLINK_NS))) return references |
def _run(self, url, auth): ''' Performs a multiprocess depth-first-search of the catalog references and yields a URL for each leaf dataset found :param str url: URL for the current catalog :param requests.auth.AuthBase auth: requets auth object to use ''' if url in self.visited: logger.debug("Skipping %s (already crawl... |
= request_xml(url, auth) for ds in self._build_catalog(url, xml_content): yield ds |
def _build_catalog(self, url, xml_content): ''' Recursive function to perform the DFS and yield the leaf datasets :param str url: URL for the current catalog :param str xml_content: XML Body returned from HTTP Request ''' try: tree = etree.XML(xml_content) except BaseException: return # Get a list of URLs references = ... |
[self.pool.apply_async(request_xml, args=(ref,)) for ref in references] responses = [j.get() for j in jobs] # This is essentially the graph traversal step for i, response in enumerate(responses): for ds in self._build_catalog(references[i], response): yield ds # Yield the leaves for ds in self._yield_leaves(url, tree):... |
def find_module(fdr, fqname, path = None): '''Find a loader for module or package `fqname`. This method will be called with the fully qualified name of the module. If the finder is installed on `sys.meta_path`, it will receive a second argument, which is `None` for a top-level module, or `package.__path__` for submodul... |
found, or `None` if it wasn't. If `find_module()` raises an exception, it will be propagated to the caller, aborting the import. [5] The path argument to `finder.find_module()` is there because the `pkg.__path__` variable may be needed at this point. It may either come from the actual parent module or be supplied by `i... |
Loader(fqname, fdr.aliases[fqname]) return None |
def load_module(ldr, fqname): '''Load `fqname` from under `ldr.fspath`. The `fqname` argument is the fully qualified module name, eg. "spam.eggs.ham". As explained above, when :: finder.find_module("spam.eggs.ham") is called, "spam.eggs" has already been imported and added to `sys.modules`. However, the `find_module()`... |
so a finder shouldn't depend on the parent package being available in `sys.modules`. The `load_module()` method has a few responsibilities that it must fulfill before it runs any code: * If there is an existing module object named 'fullname' in `sys.modules`, the loader must use that existing module. (Otherwise, the `r... |
in `sys.modules`, the loader must create a new module object and add it to `sys.modules`. Note that the module object must be in `sys.modules` before the loader executes the module code. This is crucial because the module code may (directly or indirectly) import itself; adding it to `sys.modules` beforehand prevents un... |
load fails, the loader needs to remove any module it may have inserted into `sys.modules`. If the module was already in `sys.modules` then the loader should leave it alone. * The `__file__` attribute must be set. This must be a string, but it may be a dummy value, for example "<frozen>". The privilege of not having a `... |
built-in modules. * The `__name__` attribute must be set. If one uses `imp.new_module()` then the attribute is set automatically. * If it's a package, the __path__ variable must be set. This must be a list, but may be empty if `__path__` has no further significance to the importer (more on this later). * The `__loader_... |
is mostly for introspection and reloading, but can be used for importer-specific extras, for example getting data associated with an importer. The `__package__` attribute [8] must be set. If the module is a Python module (as opposed to a built-in module or a dynamically loaded extension), it should execute the module's... |
explicit relative imports http://www.python.org/dev/peps/pep-0366/ ''' scope = ldr.scope.split('.') modpath = fqname.split('.') if scope != modpath[0:len(scope)]: raise AssertionError( "%s responsible for %s got request for %s" % ( ldr.__class__.__name__, ldr.scope, fqname, ) ) if fqname in sys.modules: mod = sys.modul... |
str(fqname.rpartition('.')[0]) exec(fs.get_code(fspath), mod.__dict__) return mod |
def zthread_fork(ctx, func, *args, **kwargs): """ Create an attached thread. An attached thread gets a ctx and a PAIR pipe back to its parent. It must monitor its pipe, and exit if the pipe becomes unreadable. Returns pipe, or NULL if there was an error. """ a = ctx.socket(zmq.PAIR) a.setsockopt(zmq.LINGER, 0) a.setsoc... |
b.setsockopt(zmq.RCVHWM, 100) b.setsockopt(zmq.SNDHWM, 100) b.setsockopt(zmq.SNDTIMEO, 5000) a.setsockopt(zmq.RCVTIMEO, 5000) iface = "inproc://%s" % binascii.hexlify(os.urandom(8)) a.bind(iface) b.connect(iface) thread = threading.Thread(target=func, args=((ctx, b) + args), kwargs=kwargs) thread.daemon = False thread.... |
def _remap(object, name, value, safe=True): """Prevent accidental assignment of existing members Arguments: object (object): Parent of new attribute name (str): Name of new attribute value (object): Value of new attribute safe (bool): Whether or not to guarantee that the new attribute was not overwritten. Can be set to... |
and safe: # Cannot alter original binding. if hasattr(object, name): raise AttributeError("Cannot override existing name: " "%s.%s" % (object.__name__, name)) # Cannot alter classes of functions if type(object).__name__ != "module": raise AttributeError("%s != 'module': Cannot alter " "anything but modules" % object) e... |
def init(): """Try loading each binding in turn Please note: the entire Qt module is replaced with this code: sys.modules["Qt"] = binding() This means no functions or variables can be called after this has executed. For debugging and testing, this module may be accessed through `Qt.__shim__`. """ preferred = os.getenv(... |
# Internal flag (used in installer) if preferred == "None": self.__wrapper_version__ = self.__version__ return preferred = preferred.split(os.pathsep) available = { "PySide2": _pyside2, "PyQt5": _pyqt5, "PySide": _pyside, "PyQt4": _pyqt4 } try: bindings = [available[binding] for binding in preferred] except KeyError: r... |
e: _log(" - ImportError(\"%s\")" % e, verbose) continue else: # Reference to this module binding.__shim__ = self binding.QtCompat = self sys.modules.update({ __name__: binding, # Fix #133, `from Qt.QtWidgets import QPushButton` __name__ + ".QtWidgets": binding.QtWidgets }) return # If not binding were found, throw this... |
def log_instantiation(LOGGER, classname, args, forbidden, with_date=False): ''' Log the instantiation of an object to the given logger. :LOGGER: A logger to log to. Please see module "logging". :classname: The name of the class that is being instantiated. :args: A dictionary of arguments passed to the instantiation, wh... |
e.g. "password". :with_date: Optional. Boolean. Indicated whether the initiation date and time should be logged. ''' # Info: if with_date: LOGGER.info('Instantiating '+classname+' at '+datetime.datetime.now().strftime('%Y-%m-%d_%H:%M')) else: LOGGER.info('Instantiating '+classname) # Debug: for argname in args: if args... |
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[ke... |
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"): rais... |
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) |
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) |
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.ReverseLookupEx... |
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='... |
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 sea... |
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... |
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 passe... |
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, Non... |
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 provi... |
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... |
unreachable? msg = 'No valid search terms have been specified.' raise ReverseLookupException(msg=msg) return query |
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_authenticat... |
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", "us... |
: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 |
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.... |
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=T... |
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 ... |
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.DoesNot... |
def nonzero(self): """ Get all non-zero bits """ return [i for i in xrange(self.size()) if self.test(i)] |
def tohexstring(self): """ Returns a hexadecimal string """ val = self.tostring() st = "{0:0x}".format(int(val, 2)) return st.zfill(len(self.bitmap)*2) |
def fromhexstring(cls, hexstring): """ Construct BitMap from hex string """ bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b") return cls.fromstring(bitstring) |
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 |
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 us... |
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 ... |
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.p... |
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 ... |
{'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 |
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... |
def setup(self): """Initialize filter just before it will be used.""" super(CleanCSSFilter, self).setup() self.root = current_app.config.get('COLLECT_STATIC_ROOT') |
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... |
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) |
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('}]);') |
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.wri... |
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.DCIExceptio... |
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 = ... |
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' |
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(*arg... |
def download(cls, url, filename=None): """ Download a file into the correct cache directory. """ return utility.download(url, cls.directory(), filename) |
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 |
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... |
return None |
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( ... |
= 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,... |
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 l... |
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) |
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 Confi... |
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) |
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.chil... |
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 member... |
':' 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 |
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 r... |
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.... |
count: break else: if elem.name == to_name: break return Builder(elem) |
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(... |
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 |
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 |
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 |
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 ... |
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-remote... |
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 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... |
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.J... |
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() |
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': ... |
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 i... |
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 |
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' :... |
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... |
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 em... |
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']]: e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.