1 from __future__ import print_function
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
9 from sfa.util.py23 import StringType
14 def __init__(self, dict=None, xml_str=None):
16 self.load_from_dict(dict)
19 xml_dict = xml.todict()
20 self.load_from_dict(xml_dict)
22 def get_field(self, field):
23 return self.__dict__.get(field, None)
26 # turns out the date_created field is received by the client as a 'created' int
27 # (and 'last_updated' does not make it at all)
29 def date_repr(self, fields):
30 if not isinstance(fields, list):
33 value = getattr(self, field, None)
34 if isinstance(value, datetime):
35 return datetime_to_string(value)
36 elif isinstance(value, (int, float)):
37 return datetime_to_string(utcparse(value))
39 return "** undef_datetime **"
42 # need to filter out results, esp. wrt relationships
43 # exclude_types must be a tuple so we can use isinstance
45 def record_to_dict(self, exclude_types=None):
46 if exclude_types is None:
51 return k.startswith('_') or isinstance(v, exclude_types)
52 keys = [k for k, v in d.items() if not exclude(k, v)]
53 return {k: d[k] for k in keys}
56 return self.save_as_xml()
58 def load_from_dict(self, d):
59 for (k, v) in d.iteritems():
61 if isinstance(v, StringType) and v.lower() in ['true']:
63 if isinstance(v, StringType) and v.lower() in ['false']:
67 # in addition we provide convenience for converting to and from xml records
68 # for this purpose only, we need the subclasses to define 'fields' as either
69 # a list or a dictionary
71 fields = self.__dict__.keys()
74 def save_as_xml(self):
75 # xxx not sure about the scope here
76 input_dict = dict([(key, getattr(self, key))
77 for key in self.fields() if getattr(self, key, None)])
78 xml_record = XML("<record />")
79 xml_record.parse_dict(input_dict)
80 return xml_record.toxml()
82 def dump(self, format=None, dump_parents=False, sort=False):
86 format = format.lower()
88 self.dump_text(dump_parents, sort=sort)
90 print(self.save_as_xml())
91 elif format == 'simple':
92 print(self.dump_simple())
94 raise Exception("Invalid format %s" % format)
96 def dump_text(self, dump_parents=False, sort=False):
99 # print remaining fields
100 fields = self.fields()
103 for attrib_name in fields:
104 attrib = getattr(self, attrib_name)
106 if attrib_name.startswith('_'):
112 if attrib_name == 'gid':
114 print(GID(string=attrib).dump_string(8, dump_parents))
115 elif attrib_name in ['date created', 'last updated']:
116 print(" %s: %s" % (attrib_name, self.date_repr(attrib_name)))
118 print(" %s: %s" % (attrib_name, attrib))
120 def dump_simple(self):