def get_uuid(session: Session, uuid: str, not_found='raise'): """ .. versionadded:: 0.1.13 Return the Metacatalog object of given version 4 UUID. The supported objects are: - Entry - EntryGroup - Keyword .. versionadded:: 0.2.7 - Person """ # check if an Entry exists entry = api.find_entry(session, uuid=uuid) if entry is not None: return entry # check if Entrygroup exists group = api.find_group(session, uuid=uuid) if group is not None: return group # check if a Person exists person = api.find_person(session, uuid=uuid) if person is not None: return person # handle keyword keyword = api.find_keyword(session, uuid=uuid) if keyword is not None: return keyword if not_found == 'raise': raise NoResultFound("The UUID='%s' was not found." % uuid) else: return None
def find(args): # get the session session = connect(args) # get the entity entity = args.entity # set by to an empty list if not given if args.by is None: args.by = [] # parse out the BY arguments kwargs = dict() for by in args.by: # if len(by) != 2: kwargs[by[0]] = by[1] # switch entity if entity.lower() == 'units' or entity.lower() == 'unit': results = api.find_unit(session, **kwargs) elif entity.lower() == 'variables' or entity.lower() == 'variable': results = api.find_variable(session, **kwargs) elif entity.lower() == 'licenses' or entity.lower() == 'license': results = api.find_license(session, **kwargs) elif entity.lower() == 'keywords' or entity.lower() == 'keyword': results = api.find_keyword(session, **kwargs) elif entity.lower() == 'roles' or entity.lower() == 'role': results = api.find_role(session, **kwargs) elif entity.lower() == 'persons' or entity.lower() == 'person': results = api.find_person(session, **kwargs) elif entity.lower() == 'group_types' or entity.lower() == 'group_type': results = api.find_group_type(session, **kwargs) elif entity.lower() == 'groups' or entity.lower() == 'group': results = api.find_group(session, **kwargs) elif entity.lower() == 'entries' or entity.lower() == 'entry': results = api.find_entry(session, **kwargs) elif entity.lower() == 'thesaurus': results = api.find_thesaurus(session, **kwargs) else: cprint(args, 'Oops. Finding %s is not supported.' % entity) exit(0) # switch the output if args.json: obj = [serialize(r) for r in results] cprint(args, json.dumps(obj, indent=4)) elif args.csv: obj = [flatten(serialize(r)) for r in results] f = io.StringIO(newline='') colnames = set([n for o in obj for n in o.keys()]) writer = csv.DictWriter(f, fieldnames=colnames, quotechar='"', quoting=csv.QUOTE_NONNUMERIC, lineterminator='\r') writer.writeheader() for o in obj: writer.writerow(o) f.seek(0) cprint(args, f.getvalue()) else: # stdOut for result in results: cprint(args, result)
def add_keywords_to_entries(session, entries, keywords, alias=None): r"""Associate keyword(s) to entrie(s) Adds associations between entries and keywords. The Entry and Keyword instances have to already exist in the database. Keywords are usually prepopulated. You might want to alias an keyword or associate a value to it. Use the alias and value lists for this. Parameters ---------- session : sqlalchemy.Session SQLAlchemy session connected to the database. entries : list List of identifier or single identifier to load entries. If int, the Entry.id is assumed. If str, title is assumed. Can also pass a metacatalog.Entry object. keywords : list List of identifier or single identifier to load keywords. If int, Keyword.id is assumed, If str, Keyword.value is assumed. Can also pass a metacatalog.Keyword object. alias : list List of, or single alias names. The shape has to match the keywords parameter. These alias will rename the keywords on association. In case one instance should not recive an alias, pass None instead. .. deprecated:: 0.4.5 'alias' will be removed with a future release Returns ------- void See Also -------- metacatalog.Entry metacatalog.Keyword """ # check the input shapes if not isinstance(entries, list): entries = [entries] if not isinstance(keywords, list): keywords = [keywords] # if not isinstance(alias, list): # alias = [alias] * len(keywords) # add for each entry for entry_id in entries: # load the entry if isinstance(entry_id, models.Entry): entry = entry_id elif isinstance(entry_id, int): # TODO sort by version descending to get the lastest entry = api.find_entry(session=session, id=entry_id, return_iterator=True).first() elif isinstance(entry_id, str): # TODO sort by version descending to get the lastest entry = api.find_entry(session=session, title=entry_id, return_iterator=True).first() else: raise AttributeError("Value '%s' not allowed for entries" % str(type(entry_id))) # add each keyword assocs = [] for keyword_id in keywords: # load the keyword if isinstance(keyword_id, models.Keyword): keyword = keyword_id elif isinstance(keyword_id, int): keyword = api.find_keyword(session=session, id=keyword_id, return_iterator=True).first() elif isinstance(keyword_id, str): keyword = api.find_keyword(session=session, value=keyword_id, return_iterator=True).first() else: raise AttributeError("Value '%s' not allowed for keywords" % str(type(keyword_id))) # create a new keyword association assocs.append( models.KeywordAssociation(entry=entry, keyword=keyword)) # add keyword to current entry try: entry.keywords.extend(assocs) session.add(entry) session.commit() except Exception as e: session.rollback() raise e
def find(args): # get the session session = connect(args) # get the entity entity = args.entity # set by to an empty list if not given if args.by is None: args.by = [] # parse out the BY arguments kwargs=dict() for by in args.by: # if len(by) != 2: kwargs[by[0]] = by[1] # switch entity if entity.lower() == 'units' or entity.lower() == 'unit': results = api.find_unit(session, **kwargs) elif entity.lower() == 'variables' or entity.lower() == 'variable': results = api.find_variable(session, **kwargs) elif entity.lower() == 'licenses' or entity.lower() == 'license': results = api.find_license(session, **kwargs) elif entity.lower() == 'keywords' or entity.lower() == 'keyword': results = api.find_keyword(session, **kwargs) elif entity.lower() == 'roles' or entity.lower() == 'role': results = api.find_role(session, **kwargs) elif entity.lower() == 'persons' or entity.lower() == 'person': results = api.find_person(session, **kwargs) elif entity.lower() == 'group_types' or entity.lower() == 'group_type': results = api.find_group_type(session, **kwargs) elif entity.lower() == 'groups' or entity.lower() == 'group': results = api.find_group(session, **kwargs) elif entity.lower() == 'entries' or entity.lower() == 'entry': if args.include_partial: kwargs['include_partial'] = True results = api.find_entry(session, **kwargs) elif entity.lower() == 'thesaurus': results = api.find_thesaurus(session, **kwargs) else: cprint(args, 'Oops. Finding %s is not supported.' % entity) exit(0) if args.export is not None and args.export != '': # only entry and group can be exported if entity.lower() not in ('entry', 'group'): cprint(args, 'Can only export entity=Entry and entity=Group') return # get the fmt and path path = args.export fmt = args.export.split('.')[-1] fmt = 'netCDF' if fmt == 'nc' else fmt # check amount of results if len(results) == 1: results[0].export(path=path, fmt=fmt) cprint(args, f'Wrote {path}.') else: for i, result in enumerate(results): path = '.'.join([*args.export.split('.')[:-1], f'_{i}', args.export.split('.')[-1]]) result.export(path=path, fmt=fmt) cprint(args, f'Wrote {len(results)} files.') return # switch the output if args.json: obj = [serialize(r) for r in results] cprint(args, json.dumps(obj, indent=4)) elif args.csv: obj = [flatten(serialize(r)) for r in results] f = io.StringIO(newline='') colnames = set([n for o in obj for n in o.keys()]) writer = csv.DictWriter(f, fieldnames=colnames, quotechar='"', quoting=csv.QUOTE_NONNUMERIC, lineterminator='\r') writer.writeheader() for o in obj: writer.writerow(o) f.seek(0) cprint(args, f.getvalue()) else: # stdOut for result in results: cprint(args, result)