1 from manifold.core.query import Query
2 from manifoldapi.manifoldapi import execute_query
4 from django.http import HttpResponse
11 # handles serialization of datetime in json
12 DateEncoder = lambda obj: obj.strftime("%B %d, %Y %H:%M:%S") if isinstance(obj, datetime.datetime) else None
14 # support converting decimal in json
15 json.encoder.FLOAT_REPR = lambda o: format(o, '.2f')
17 # handles decimal numbers serialization in json
18 class DecimalEncoder(json.JSONEncoder):
19 def _iterencode(self, o, markers=None):
20 if isinstance(o, decimal.Decimal):
21 return (str(o) for o in [o])
22 return super(DecimalEncoder, self)._iterencode(o, markers)
24 class ObjectRequest(object):
26 def __init__(self, request, object_type, object_name):
27 self.type = object_type
28 self.name = object_name
34 self.request = request
36 if ((self.type == 'platform') or (self.type == 'testbed')) :
37 self.type = 'local:platform'
39 self.fields = ['platform', 'platform_longname', 'platform_url', 'platform_description','gateway_type'];
40 self.filters['disabled'] = '0'
41 self.filters['gateway_type'] = 'sfa'
42 self.filters['platform'] = '!myslice'
43 #elif(self.type.startswith('local:')):
44 elif ':' in self.type:
45 table = self.type.split(':')
50 # XXX TODO: find a generic Query to get the fields like
51 # select column.name from local:object where table == local:user
52 table = self.type.split(':')
55 self.id = table + '_id'
56 self.fields = ['user_id', 'email', 'password', 'config','status'];
57 elif table == "account":
58 # XXX TODO: Multiple key for account = (platform_id, user_id)
59 self.id = "platform_id, user_id"
60 self.fields = ['platform_id', 'user_id', 'auth_type', 'config'];
61 elif table == "platform":
63 self.fields = ['platform', 'platform_longname', 'platform_url', 'platform_description','gateway_type'];
65 # If we use prefix, set the key without the prefix then add it again
69 self.type = prefix + ':' + table
75 # What about key formed of multiple fields???
76 query = Query.get('local:object').filter_by('table', '==', self.type).select('key')
77 results = execute_query(self.request, query)
78 print "key of object = %s" % results
80 for r in results[0]['key'] :
83 raise Exception, 'Manifold db error'
85 def setLocalFields(self):
86 query = Query.get('local:object').filter_by('table', '==', self.type).select('column.name')
87 results = execute_query(self.request, query)
89 for r in results[0]['column'] :
90 self.fields.append(r['name'])
92 raise Exception, 'Manifold db error'
94 def setFields(self, fields):
95 # selected_fields = []
97 # if p in self.fields :
98 # selected_fields.append(p)
102 def applyFilters(self, query, force_filters = False):
103 if (force_filters and not self.filters) :
104 raise Exception, "Filters required"
106 for k, f in self.filters.iteritems() :
108 query.filter_by(k, '!=', f[1:])
109 elif (f[:2] == ">=") :
110 query.filter_by(k, '>=', f[2:])
111 elif (f[:1] == ">") :
112 query.filter_by(k, '>', f[1:])
113 elif (f[:2] == "<=") :
114 query.filter_by(k, '<=', f[2:])
115 elif (f[:1] == "<") :
116 query.filter_by(k, '<', f[1:])
118 query.filter_by(k, '==', f)
122 query = Query.get(self.type)
123 if (self.id is not None) and (self.id not in self.fields) :
124 query.select(self.fields + [self.id])
126 query.select(self.fields)
128 query = self.applyFilters(query)
129 return execute_query(self.request, query)
132 query = Query.create(self.type)
133 # No filters for create
135 for p in self.params :
136 for k,v in p.iteritems() :
137 print "param: %s : %s" % (k,v)
139 print "query = ",query
141 raise Exception, "Params are required for create"
142 return execute_query(self.request, query)
145 query = Query.update(self.type)
146 query = self.applyFilters(query, True)
149 for p in self.params :
150 for k,v in p.iteritems() :
151 print "param: %s : %s" % (k,v)
153 print "query = ",query
155 raise Exception, "Params are required for update"
157 if self.id is not None:
158 query.select(self.id)
160 return execute_query(self.request, query)
163 query = Query.delete(self.type)
164 query = self.applyFilters(query, True)
166 query.set(self.filters)
168 raise Exception, "Filters are required for delete"
169 return execute_query(self.request, query)
172 return HttpResponse(json.dumps(self.get(), cls=DecimalEncoder, default=DateEncoder), content_type="application/json")
175 response = self.get()
177 response_data['fields'] = self.fields
178 response_data['labels'] = self.fields
179 response_data['data'] = []
180 response_data['total'] = len(response)
183 for p in self.fields :
185 response_data['data'].append(d)
187 return HttpResponse(json.dumps(response_data, cls=DecimalEncoder, default=DateEncoder), content_type="application/json")
190 return HttpResponse(json.dumps({'error' : msg}), content_type="application/json")
193 return HttpResponse(json.dumps({'success' : msg}), content_type="application/json")