1 from sfa.util.sfatime import utcparse, datetime_to_string
2 from types import StringTypes
3 from datetime import datetime
4 from sfa.util.xml import XML
5 from sfa.trust.gid import GID
7 from sfa.util.sfalogging import logger
11 def __init__(self, dict=None, xml_str=None):
13 self.load_from_dict(dict)
16 xml_dict = xml.todict()
17 self.load_from_dict(xml_dict)
19 def get_field(self, field):
20 return self.__dict__.get(field, None)
23 # turns out the date_created field is received by the client as a 'created' int
24 # (and 'last_updated' does not make it at all)
26 def date_repr (self,fields):
27 if not isinstance(fields,list):
30 value = getattr(self,field,None)
31 if isinstance (value,datetime):
32 return datetime_to_string (value)
33 elif isinstance (value,(int,float)):
34 return datetime_to_string(utcparse(value))
36 return "** undef_datetime **"
39 # need to filter out results, esp. wrt relationships
40 # exclude_types must be a tuple so we can use isinstance
42 def record_to_dict (self, exclude_types=None):
43 if exclude_types is None:
47 return k.startswith('_') or isinstance (v, exclude_types)
48 keys = [ k for k, v in d.items() if not exclude(k, v) ]
49 return { k : d[k] for k in keys }
52 return self.save_as_xml()
54 def load_from_dict (self, d):
55 for (k,v) in d.iteritems():
57 if isinstance(v, StringTypes) and v.lower() in ['true']:
59 if isinstance(v, StringTypes) and v.lower() in ['false']:
63 # in addition we provide convenience for converting to and from xml records
64 # for this purpose only, we need the subclasses to define 'fields' as either
65 # a list or a dictionary
67 fields = self.__dict__.keys()
70 def save_as_xml (self):
71 # xxx not sure about the scope here
72 input_dict = dict( [ (key, getattr(self,key)) for key in self.fields() if getattr(self,key,None) ] )
73 xml_record = XML("<record />")
74 xml_record.parse_dict(input_dict)
75 return xml_record.toxml()
77 def dump(self, format=None, dump_parents=False, sort=False):
81 format = format.lower()
83 self.dump_text(dump_parents,sort=sort)
85 print self.save_as_xml()
86 elif format == 'simple':
87 print self.dump_simple()
89 raise Exception, "Invalid format %s" % format
91 def dump_text(self, dump_parents=False, sort=False):
94 # print remaining fields
95 fields = self.fields()
96 if sort: fields.sort()
97 for attrib_name in fields:
98 attrib = getattr(self, attrib_name)
100 if attrib_name.startswith('_'): continue
102 if callable (attrib): continue
104 if attrib_name == 'gid':
106 print GID(string=attrib).dump_string(8, dump_parents)
107 elif attrib_name in ['date created', 'last updated']:
108 print " %s: %s" % (attrib_name, self.date_repr(attrib_name))
110 print " %s: %s" % (attrib_name, attrib)
112 def dump_simple(self):