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
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:
49 return k.startswith('_') or isinstance (v, exclude_types)
50 keys = [ k for k, v in d.items() if not exclude(k, v) ]
51 return { k : d[k] for k in keys }
54 return self.save_as_xml()
56 def load_from_dict (self, d):
57 for (k,v) in d.iteritems():
59 if isinstance(v, StringType) and v.lower() in ['true']:
61 if isinstance(v, StringType) and v.lower() in ['false']:
65 # in addition we provide convenience for converting to and from xml records
66 # for this purpose only, we need the subclasses to define 'fields' as either
67 # a list or a dictionary
69 fields = self.__dict__.keys()
72 def save_as_xml (self):
73 # xxx not sure about the scope here
74 input_dict = dict( [ (key, getattr(self,key)) for key in self.fields() if getattr(self,key,None) ] )
75 xml_record = XML("<record />")
76 xml_record.parse_dict(input_dict)
77 return xml_record.toxml()
79 def dump(self, format=None, dump_parents=False, sort=False):
83 format = format.lower()
85 self.dump_text(dump_parents,sort=sort)
87 print(self.save_as_xml())
88 elif format == 'simple':
89 print(self.dump_simple())
91 raise Exception("Invalid format %s" % format)
93 def dump_text(self, dump_parents=False, sort=False):
96 # print remaining fields
97 fields = self.fields()
98 if sort: fields.sort()
99 for attrib_name in fields:
100 attrib = getattr(self, attrib_name)
102 if attrib_name.startswith('_'): continue
104 if callable (attrib): continue
106 if attrib_name == 'gid':
108 print(GID(string=attrib).dump_string(8, dump_parents))
109 elif attrib_name in ['date created', 'last updated']:
110 print(" %s: %s" % (attrib_name, self.date_repr(attrib_name)))
112 print(" %s: %s" % (attrib_name, attrib))
114 def dump_simple(self):