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 # turns out the date_created field is received by the client as a 'created' int
19 # (and 'last_updated' does not make it at all)
21 def date_repr (self,fields):
22 if not isinstance(fields,list): fields=[fields]
24 value=getattr(self,field,None)
25 if isinstance (value,datetime):
26 return datetime_to_string (value)
27 elif isinstance (value,(int,float)):
28 return datetime_to_string(utcparse(value))
30 return "** undef_datetime **"
34 keys=[k for k in d.keys() if not k.startswith('_')]
35 return dict ( [ (k,d[k]) for k in keys ] )
38 return self.save_as_xml()
40 def load_from_dict (self, d):
41 for (k,v) in d.iteritems():
43 if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
44 if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
47 # in addition we provide convenience for converting to and from xml records
48 # for this purpose only, we need the subclasses to define 'fields' as either
49 # a list or a dictionary
50 def xml_fields (self):
51 fields = self.__dict__.keys()
54 def save_as_xml (self):
55 # xxx not sure about the scope here
56 input_dict = dict( [ (key, getattr(self,key)) for key in self.xml_fields() if getattr(self,key,None) ] )
57 xml_record=XML("<record />")
58 xml_record.parse_dict (input_dict)
59 return xml_record.toxml()
61 def dump(self, format=None, dump_parents=False):
65 format = format.lower()
67 self.dump_text(dump_parents)
69 print self.save_to_string()
70 elif format == 'simple':
71 print self.dump_simple()
73 raise Exception, "Invalid format %s" % format
75 def dump_text(self, dump_parents=False):
76 # print core fields in this order
77 core_fields = [ 'hrn', 'type', 'authority', 'date_created', 'created', 'last_updated', 'gid', ]
78 print "".join(['=' for i in range(40)])
80 print " hrn:", self.hrn
81 print " type:", self.type
82 print " authority:", self.authority
83 print " date created:", self.date_repr( ['date_created','created'] )
84 print " last updated:", self.date_repr('last_updated')
87 print GID(self.gid).dump_string(8, dump_parents)
89 # print remaining fields
90 for attrib_name in dir(self):
91 attrib = getattr(self, attrib_name)
93 if attrib_name.startswith('_'): continue
95 if attrib_name in core_fields: continue
97 if callable (attrib): continue
98 print " %s: %s" % (attrib_name, attrib)
100 def dump_simple(self):