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
9 def __init__(self, dict=None, xml=None):
11 self.load_from_dict(dict)
14 xml_dict = xml_record.todict()
15 self.load_from_dict(xml_dict)
18 def get_field(self, field):
19 return self.__dict__.get(field, None)
22 # turns out the date_created field is received by the client as a 'created' int
23 # (and 'last_updated' does not make it at all)
25 def date_repr (self,fields):
26 if not isinstance(fields,list): fields=[fields]
28 value=getattr(self,field,None)
29 if isinstance (value,datetime):
30 return datetime_to_string (value)
31 elif isinstance (value,(int,float)):
32 return datetime_to_string(utcparse(value))
34 return "** undef_datetime **"
38 keys=[k for k in d.keys() if not k.startswith('_')]
39 return dict ( [ (k,d[k]) for k in keys ] )
42 return self.save_as_xml()
44 def load_from_dict (self, d):
45 for (k,v) in d.iteritems():
47 if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
48 if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
51 # in addition we provide convenience for converting to and from xml records
52 # for this purpose only, we need the subclasses to define 'fields' as either
53 # a list or a dictionary
55 fields = self.__dict__.keys()
58 def save_as_xml (self):
59 # xxx not sure about the scope here
60 input_dict = dict( [ (key, getattr(self,key)) for key in self.fields() if getattr(self,key,None) ] )
61 xml_record=XML("<record />")
62 xml_record.parse_dict (input_dict)
63 return xml_record.toxml()
65 def dump(self, format=None, dump_parents=False, sort=False):
69 format = format.lower()
71 self.dump_text(dump_parents,sort=sort)
73 print self.save_as_xml()
74 elif format == 'simple':
75 print self.dump_simple()
77 raise Exception, "Invalid format %s" % format
79 def dump_text(self, dump_parents=False, sort=False):
82 # print remaining fields
84 if sort: fields.sort()
85 for attrib_name in fields:
86 attrib = getattr(self, attrib_name)
88 if attrib_name.startswith('_'): continue
90 if callable (attrib): continue
92 if attrib_name == 'gid':
94 print GID(attrib).dump_string(8, dump_parents)
95 elif attrib_name in ['date created', 'last updated']:
96 print " %s: %s" % (attrib_name, self.date_repr(attrib_name))
98 print " %s: %s" % (attrib_name, attrib)
100 def dump_simple(self):