3 from sfa.util.sfatime import utcparse, datetime_to_string
4 from datetime import datetime
5 from sfa.util.xml import XML
6 from sfa.trust.gid import GID
8 from sfa.util.sfalogging import logger
13 def __init__(self, dict=None, xml_str=None):
15 self.load_from_dict(dict)
18 xml_dict = xml.todict()
19 self.load_from_dict(xml_dict)
21 def get_field(self, field):
22 return self.__dict__.get(field, None)
25 # turns out the date_created field is received by the client as a 'created' int
26 # (and 'last_updated' does not make it at all)
28 def date_repr(self, fields):
29 if not isinstance(fields, list):
32 value = getattr(self, field, None)
33 if isinstance(value, datetime):
34 return datetime_to_string(value)
35 elif isinstance(value, (int, float)):
36 return datetime_to_string(utcparse(value))
38 return "** undef_datetime **"
41 # need to filter out results, esp. wrt relationships
42 # exclude_types must be a tuple so we can use isinstance
44 def record_to_dict(self, exclude_types=None):
45 if exclude_types is None:
50 return k.startswith('_') or isinstance(v, exclude_types)
51 keys = [k for k, v in list(d.items()) if not exclude(k, v)]
52 return {k: d[k] for k in keys}
55 return self.save_as_xml()
57 def load_from_dict(self, d):
58 for (k, v) in d.items():
60 if isinstance(v, str) and v.lower() in ['true']:
62 if isinstance(v, str) and v.lower() in ['false']:
66 # in addition we provide convenience for converting to and from xml records
67 # for this purpose only, we need the subclasses to define 'fields' as either
68 # a list or a dictionary
70 fields = list(self.__dict__.keys())
73 def save_as_xml(self):
74 # xxx not sure about the scope here
75 input_dict = dict([(key, getattr(self, key))
76 for key in self.fields() if getattr(self, key, None)])
77 xml_record = XML("<record />")
78 xml_record.parse_dict(input_dict)
79 return xml_record.toxml()
81 def dump(self, format=None, dump_parents=False, sort=False):
85 format = format.lower()
87 self.dump_text(dump_parents, sort=sort)
89 print(self.save_as_xml())
90 elif format == 'simple':
91 print(self.dump_simple())
93 raise Exception("Invalid format %s" % format)
95 def dump_text(self, dump_parents=False, sort=False):
98 # print remaining fields
99 fields = self.fields()
102 for attrib_name in fields:
103 attrib = getattr(self, attrib_name)
105 if attrib_name.startswith('_'):
111 if attrib_name == 'gid':
113 print(GID(string=attrib).dump_string(8, dump_parents))
114 elif attrib_name in ['date created', 'last updated']:
115 print(" %s: %s" % (attrib_name, self.date_repr(attrib_name)))
117 print(" %s: %s" % (attrib_name, attrib))
119 def dump_simple(self):