def to_dict(self, deep=False, stringify=False) -> dict: """To dict Return the model as a python dictionary. .. versionchanged:: 0.3.8 added stringify option Parameters ---------- deep : bool If True, all related objects will be included as dictionary. Defaults to False stringify : bool If True, all values will be turned into a string, to make the object serializable. Returns ------- obj : dict The Model as dict """ # base dictionary d = dict(id=self.id, uuid=self.uuid, type=self.type.to_dict(deep=False), publication=self.publication, lastUpdate=self.lastUpdate) # set optionals for attr in ('title', 'description'): if hasattr(self, attr) and getattr(self, attr) is not None: d[attr] = getattr(self, attr) # lazy loading if deep: d['entries'] = [ e.to_dict(stringify=stringify) for e in self.entries ] else: d['entries'] = [e.uuid for e in self.entries] # serialize if stringify: d = serialize(d, stringify=True) return d
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 to_dict(self, deep=False, stringify=False) -> dict: """To dict Return the model as a python dictionary. Parameters ---------- deep : bool If True, all related objects will be included as dictionary. Defaults to False stringify : bool If True, all values will be turned into a string, to make the object serializable. Returns ------- obj : dict The Model as dict """ # base dictionary d = dict(id=self.id, uuid=self.uuid, title=self.title, author=self.author.to_dict(deep=False), authors=[a.to_dict(deep=False) for a in self.authors], locationShape=self.location_shape.wkt, location=self.location_shape.wkt, variable=self.variable.to_dict(deep=False), embargo=self.embargo, embargo_end=self.embargo_end, version=self.version, isPartial=self.is_partial, publication=self.publication, lastUpdate=self.lastUpdate, keywords=self.plain_keywords_dict()) # optional relations if self.license is not None: d['license'] = self.license.to_dict(deep=False) if self.details is not None: d['details'] = self.details_dict(full=True) if self.datasource is not None: d['datasource'] = self.datasource.to_dict(deep=False) # set optional attributes for attr in ('abstract', 'external_id', 'comment', 'citation'): if hasattr(self, attr) and getattr(self, attr) is not None: d[attr] = getattr(self, attr) # lazy loading if deep: projects = self.projects if len(projects) > 0: d['projects'] = [p.to_dict(deep=False) for p in projects] comp = self.composite_entries if len(comp) > 0: d['composite_entries'] = [e.to_dict(deep=False) for e in comp] if stringify: return serialize(d, stringify=True) return d
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)