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