huge cleanup for removing mutables used as default
[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
18     def get_field(self, field):
19         return self.__dict__.get(field, None)
20
21     # xxx fixme
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)
24     # let's be flexible
25     def date_repr (self,fields):
26         if not isinstance(fields,list): fields=[fields]
27         for field in 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))
33         # fallback
34         return "** undef_datetime **"
35     
36     # it may be important to exclude relationships, which fortunately
37     # 
38     def todict (self, exclude_types=None):
39         if exclude_types is None: exclude_types=[]
40         d=self.__dict__
41         def exclude (k,v):
42             if k.startswith('_'): return True
43             if exclude_types:
44                 for exclude_type in exclude_types:
45                     if isinstance (v,exclude_type): return True
46             return False
47         keys=[k for (k,v) in d.items() if not exclude(k,v)]
48         return dict ( [ (k,d[k]) for k in keys ] )
49     
50     def toxml(self):
51         return self.save_as_xml()
52
53     def load_from_dict (self, d):
54         for (k,v) in d.iteritems():
55             # experimental
56             if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
57             if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
58             setattr(self,k,v)
59
60     # in addition we provide convenience for converting to and from xml records
61     # for this purpose only, we need the subclasses to define 'fields' as either
62     # a list or a dictionary
63     def fields (self):
64         fields = self.__dict__.keys()
65         return fields
66
67     def save_as_xml (self):
68         # xxx not sure about the scope here
69         input_dict = dict( [ (key, getattr(self,key)) for key in self.fields() if getattr(self,key,None) ] )
70         xml_record=XML("<record />")
71         xml_record.parse_dict (input_dict)
72         return xml_record.toxml()
73
74     def dump(self, format=None, dump_parents=False, sort=False):
75         if not format:
76             format = 'text'
77         else:
78             format = format.lower()
79         if format == 'text':
80             self.dump_text(dump_parents,sort=sort)
81         elif format == 'xml':
82             print self.save_as_xml()
83         elif format == 'simple':
84             print self.dump_simple()
85         else:
86             raise Exception, "Invalid format %s" % format
87
88     def dump_text(self, dump_parents=False, sort=False):
89         print 40*'='
90         print "RECORD"
91         # print remaining fields
92         fields=self.fields()
93         if sort: fields.sort()
94         for attrib_name in fields:
95             attrib = getattr(self, attrib_name)
96             # skip internals
97             if attrib_name.startswith('_'):     continue
98             # skip callables
99             if callable (attrib):               continue
100             # handle gid 
101             if attrib_name == 'gid':
102                 print "    gid:"      
103                 print GID(string=attrib).dump_string(8, dump_parents)
104             elif attrib_name in ['date created', 'last updated']:
105                 print "    %s: %s" % (attrib_name, self.date_repr(attrib_name))
106             else:
107                 print "    %s: %s" % (attrib_name, attrib)
108
109     def dump_simple(self):
110         return "%s"%self