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 ] )
37 def load_from_dict (self, d):
38 for (k,v) in d.iteritems():
40 if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
41 if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
44 # in addition we provide convenience for converting to and from xml records
45 # for this purpose only, we need the subclasses to define 'fields' as either
46 # a list or a dictionary
47 def xml_fields (self):
49 if isinstance(fields,dict): fields=fields.keys()
52 def save_as_xml (self):
53 # xxx not sure about the scope here
54 input_dict = dict( [ (key, getattr(self.key), ) for key in self.xml_fields() if getattr(self,key,None) ] )
55 xml_record=XML("<record />")
56 xml_record.parse_dict (input_dict)
57 return xml_record.toxml()
59 def dump(self, format=None, dump_parents=False):
63 format = format.lower()
65 self.dump_text(dump_parents)
67 print self.save_to_string()
68 elif format == 'simple':
69 print self.dump_simple()
71 raise Exception, "Invalid format %s" % format
73 def dump_text(self, dump_parents=False):
74 # print core fields in this order
75 core_fields = [ 'hrn', 'type', 'authority', 'date_created', 'created', 'last_updated', 'gid', ]
76 print "".join(['=' for i in range(40)])
78 print " hrn:", self.hrn
79 print " type:", self.type
80 print " authority:", self.authority
81 print " date created:", self.date_repr( ['date_created','created'] )
82 print " last updated:", self.date_repr('last_updated')
85 print GID(self.gid).dump_string(8, dump_parents)
87 # print remaining fields
88 for attrib_name in dir(self):
89 attrib = getattr(self, attrib_name)
91 if attrib_name.startswith('_'): continue
93 if attrib_name in core_fields: continue
95 if callable (attrib): continue
96 print " %s: %s" % (attrib_name, attrib)
98 def dump_simple(self):