a4a87b49df1b740e4c172177804de1b1e49c58a2
[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=None):
12         if dict:
13             self.load_from_dict(dict)
14         elif xml:
15             xml_record = XML(xml)
16             xml_dict = xml_record.todict()
17             self.load_from_dict(xml_dict)  
18
19
20     def get_field(self, field):
21         return self.__dict__.get(field, None)
22
23     # xxx fixme
24     # turns out the date_created field is received by the client as a 'created' int
25     # (and 'last_updated' does not make it at all)
26     # let's be flexible
27     def date_repr (self,fields):
28         if not isinstance(fields,list): 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 todict (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']: v=True
58             if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
59             setattr(self,k,v)
60
61     # in addition we provide convenience for converting to and from xml records
62     # for this purpose only, we need the subclasses to define 'fields' as either
63     # a list or a dictionary
64     def fields (self):
65         fields = self.__dict__.keys()
66         return fields
67
68     def save_as_xml (self):
69         # xxx not sure about the scope here
70         input_dict = dict( [ (key, getattr(self,key)) for key in self.fields() if getattr(self,key,None) ] )
71         xml_record=XML("<record />")
72         xml_record.parse_dict (input_dict)
73         return xml_record.toxml()
74
75     def dump(self, format=None, dump_parents=False, sort=False):
76         if not format:
77             format = 'text'
78         else:
79             format = format.lower()
80         if format == 'text':
81             self.dump_text(dump_parents,sort=sort)
82         elif format == 'xml':
83             print self.save_as_xml()
84         elif format == 'simple':
85             print self.dump_simple()
86         else:
87             raise Exception, "Invalid format %s" % format
88
89     def dump_text(self, dump_parents=False, sort=False):
90         print 40*'='
91         print "RECORD"
92         # print remaining fields
93         fields=self.fields()
94         if sort: fields.sort()
95         for attrib_name in fields:
96             attrib = getattr(self, attrib_name)
97             # skip internals
98             if attrib_name.startswith('_'):     continue
99             # skip callables
100             if callable (attrib):               continue
101             # handle gid 
102             if attrib_name == 'gid':
103                 print "    gid:"      
104                 print GID(string=attrib).dump_string(8, dump_parents)
105             elif attrib_name in ['date created', 'last updated']:
106                 print "    %s: %s" % (attrib_name, self.date_repr(attrib_name))
107             else:
108                 print "    %s: %s" % (attrib_name, attrib)
109
110     def dump_simple(self):
111         return "%s"%self