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