fix save_as_xml()
[sfa.git] / sfa / storage / record.py
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
6
7 class Record:
8
9     def __init__(self, dict=None, xml=None):
10         if dict:
11             self.load_from_dict(dict)
12         elif xml:
13             xml_record = XML(xml)
14             xml_dict = xml_record.todict()
15             self.load_from_dict(xml_dict)  
16
17     # xxx fixme
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)
20     # let's be flexible
21     def date_repr (self,fields):
22         if not isinstance(fields,list): fields=[fields]
23         for field in 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))
29         # fallback
30         return "** undef_datetime **"
31     
32     def todict (self):
33         d=self.__dict__
34         keys=[k for k in d.keys() if not k.startswith('_')]
35         return dict ( [ (k,d[k]) for k in keys ] )
36     
37     def toxml(self):
38         return self.save_as_xml()
39
40     def load_from_dict (self, d):
41         for (k,v) in d.iteritems():
42             # experimental
43             if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
44             if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
45             setattr(self,k,v)
46
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()
52         return fields
53
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()
60
61     def dump(self, format=None, dump_parents=False):
62         if not format:
63             format = 'text'
64         else:
65             format = format.lower()
66         if format == 'text':
67             self.dump_text(dump_parents)
68         elif format == 'xml':
69             print self.save_to_string()
70         elif format == 'simple':
71             print self.dump_simple()
72         else:
73             raise Exception, "Invalid format %s" % format
74
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)])
79         print "RECORD"
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')
85         print "    gid:"
86         if self.gid:
87             print GID(self.gid).dump_string(8, dump_parents)    
88
89         # print remaining fields
90         for attrib_name in dir(self):
91             attrib = getattr(self, attrib_name)
92             # skip internals
93             if attrib_name.startswith('_'):     continue
94             # skip core fields
95             if attrib_name in core_fields:      continue
96             # skip callables
97             if callable (attrib):               continue
98             print "     %s: %s" % (attrib_name, attrib)
99
100     def dump_simple(self):
101         return "%s"%self