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
7 from sfa.util.sfalogging import logger
11 def __init__(self, dict=None, xml_str=None):
13 self.load_from_dict(dict)
16 xml_dict = xml.todict()
17 self.load_from_dict(xml_dict)
20 def get_field(self, field):
21 return self.__dict__.get(field, None)
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)
27 def date_repr (self,fields):
28 if not isinstance(fields,list): fields=[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))
36 return "** undef_datetime **"
39 # need to filter out results, esp. wrt relationships
40 # exclude_types must be a tuple so we can use isinstance
42 def record_to_dict (self, exclude_types=None):
43 if exclude_types is None:
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 }
52 return self.save_as_xml()
54 def load_from_dict (self, d):
55 for (k,v) in d.iteritems():
57 if isinstance(v, StringTypes) and v.lower() in ['true']: v=True
58 if isinstance(v, StringTypes) and v.lower() in ['false']: v=False
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
65 fields = self.__dict__.keys()
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()
75 def dump(self, format=None, dump_parents=False, sort=False):
79 format = format.lower()
81 self.dump_text(dump_parents,sort=sort)
83 print self.save_as_xml()
84 elif format == 'simple':
85 print self.dump_simple()
87 raise Exception, "Invalid format %s" % format
89 def dump_text(self, dump_parents=False, sort=False):
92 # print remaining fields
94 if sort: fields.sort()
95 for attrib_name in fields:
96 attrib = getattr(self, attrib_name)
98 if attrib_name.startswith('_'): continue
100 if callable (attrib): continue
102 if attrib_name == '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))
108 print " %s: %s" % (attrib_name, attrib)
110 def dump_simple(self):