8600723a0e378d3fd11222c32bd94d565928cc48
[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 from sfa.util.sfalogging import logger
8
9 class Record:
10
11     def __init__(self, dict=None, xml_str=None):
12         if dict:
13             self.load_from_dict(dict)
14         elif xml_str:
15             xml = XML(xml_str)
16             xml_dict = xml.todict()
17             self.load_from_dict(xml_dict)  
18
19     def get_field(self, field):
20         return self.__dict__.get(field, None)
21
22     # xxx fixme
23     # turns out the date_created field is received by the client as a 'created' int
24     # (and 'last_updated' does not make it at all)
25     # let's be flexible
26     def date_repr (self,fields):
27         if not isinstance(fields,list):
28             fields = [fields]
29         for field in fields:
30             value = getattr(self,field,None)
31             if isinstance (value,datetime):
32                 return datetime_to_string (value)
33             elif isinstance (value,(int,float)):
34                 return datetime_to_string(utcparse(value))
35         # fallback
36         return "** undef_datetime **"
37     
38     #
39     # need to filter out results, esp. wrt relationships
40     # exclude_types must be a tuple so we can use isinstance
41     # 
42     def record_to_dict (self, exclude_types=None):
43         if exclude_types is None:
44             exclude_types = ()
45         d = self.__dict__
46         def exclude (k, v):
47             return k.startswith('_') or isinstance (v, exclude_types)
48         keys = [ k for k, v in d.items() if not exclude(k, v) ]
49         return { k : d[k] for k in keys }
50     
51     def toxml(self):
52         return self.save_as_xml()
53
54     def load_from_dict (self, d):
55         for (k,v) in d.iteritems():
56             # experimental
57             if isinstance(v, StringTypes) and v.lower() in ['true']:
58                 v = True
59             if isinstance(v, StringTypes) and v.lower() in ['false']:
60                 v = False
61             setattr(self, k, v)
62
63     # in addition we provide convenience for converting to and from xml records
64     # for this purpose only, we need the subclasses to define 'fields' as either
65     # a list or a dictionary
66     def fields (self):
67         fields = self.__dict__.keys()
68         return fields
69
70     def save_as_xml (self):
71         # xxx not sure about the scope here
72         input_dict = dict( [ (key, getattr(self,key)) for key in self.fields() if getattr(self,key,None) ] )
73         xml_record = XML("<record />")
74         xml_record.parse_dict(input_dict)
75         return xml_record.toxml()
76
77     def dump(self, format=None, dump_parents=False, sort=False):
78         if not format:
79             format = 'text'
80         else:
81             format = format.lower()
82         if format == 'text':
83             self.dump_text(dump_parents,sort=sort)
84         elif format == 'xml':
85             print self.save_as_xml()
86         elif format == 'simple':
87             print self.dump_simple()
88         else:
89             raise Exception, "Invalid format %s" % format
90
91     def dump_text(self, dump_parents=False, sort=False):
92         print 40*'='
93         print "RECORD"
94         # print remaining fields
95         fields = self.fields()
96         if sort: fields.sort()
97         for attrib_name in fields:
98             attrib = getattr(self, attrib_name)
99             # skip internals
100             if attrib_name.startswith('_'):     continue
101             # skip callables
102             if callable (attrib):               continue
103             # handle gid 
104             if attrib_name == 'gid':
105                 print "    gid:"      
106                 print GID(string=attrib).dump_string(8, dump_parents)
107             elif attrib_name in ['date created', 'last updated']:
108                 print "    %s: %s" % (attrib_name, self.date_repr(attrib_name))
109             else:
110                 print "    %s: %s" % (attrib_name, attrib)
111
112     def dump_simple(self):
113         return "%s"%self