Merge branch 'fibre' of ssh://git.onelab.eu/git/myslice into fibre
[unfold.git] / rest / __init__.py
1 from manifold.core.query            import Query
2 from manifoldapi.manifoldapi        import execute_query
3
4 from django.http                    import HttpResponse
5
6
7 import decimal
8 import datetime
9 import json
10
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
13
14 # support converting decimal in json
15 json.encoder.FLOAT_REPR = lambda o: format(o, '.2f')
16
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)
23     
24 class ObjectRequest(object):
25     
26     def __init__(self, request, object_type, object_name):
27         self.type = object_type
28         self.name = object_name
29         self.fields = []
30         self.params = []
31         self.filters = {}
32         self.options = None
33
34         self.request = request
35         
36         if ((self.type == 'platform') or (self.type == 'testbed')) :
37             self.type = 'local:platform'
38             self.id = '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(':')
46             prefix = table[0]
47             table = table[1]
48
49             if prefix is 'local':
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(':')
53                 table = table[1]
54                 if table == "user":
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":
62                     self.id = 'platform'
63                     self.fields = ['platform', 'platform_longname', 'platform_url', 'platform_description','gateway_type'];
64             else:
65                 # If we use prefix, set the key without the prefix then add it again
66                 self.type = table
67                 self.setKey()
68                 self.setLocalFields()
69                 self.type = prefix + ':' + table
70         else :
71             self.setKey()
72             self.setLocalFields()
73     
74     def setKey(self):
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
79         if results :
80             for r in results[0]['key'] :
81                 self.id = r
82         else :
83             raise Exception, 'Manifold db error'
84     
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)
88         if results :
89             for r in results[0]['column'] :
90                 self.fields.append(r['name'])
91         else :
92             raise Exception, 'Manifold db error'
93     
94     def setFields(self, fields):
95 #         selected_fields = []
96 #         for p in fields :
97 #             if p in self.fields :
98 #                 selected_fields.append(p)
99         self.fields = fields
100         
101     
102     def applyFilters(self, query, force_filters = False):
103         if (force_filters and not self.filters) :
104             raise Exception, "Filters required"
105         if self.filters :
106             for k, f in self.filters.iteritems() :
107                 if (f[:1] == "!") :
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:])
117                 else :
118                     query.filter_by(k, '==', f)
119         return query
120     
121     def get(self):
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])
125         else :
126             query.select(self.fields)
127         
128         query = self.applyFilters(query)
129         return execute_query(self.request, query)
130
131     def create(self):
132         query = Query.create(self.type)
133         # No filters for create
134         if self.params :
135             for p in self.params :
136                 for k,v in p.iteritems() :
137                     print "param: %s : %s" % (k,v)
138                     query.set({k : v})
139             print "query = ",query
140         else:
141             raise Exception, "Params are required for create"
142         return execute_query(self.request, query)
143    
144     def update(self):
145         query = Query.update(self.type)
146         query = self.applyFilters(query, True)
147
148         if self.params :
149             for p in self.params :
150                 for k,v in p.iteritems() :
151                     print "param: %s : %s" % (k,v)
152                     query.set({k : v})
153             print "query = ",query
154         else:
155             raise Exception, "Params are required for update"
156
157         if self.id is not None:
158            query.select(self.id)
159        
160         return execute_query(self.request, query)
161     
162     def delete(self):
163         query = Query.delete(self.type)
164         query = self.applyFilters(query, True)
165         if self.filters :
166             query.set(self.filters)
167         else:
168             raise Exception, "Filters are required for delete"
169         return execute_query(self.request, query)
170     
171     def json(self):
172         return HttpResponse(json.dumps(self.get(), cls=DecimalEncoder, default=DateEncoder), content_type="application/json")
173     
174     def datatable(self):
175         response = self.get()
176         response_data = {}
177         response_data['fields'] = self.fields
178         response_data['labels'] = self.fields
179         response_data['data'] = []
180         response_data['total'] = len(response)
181         for r in response :
182             d = []
183             for p in self.fields :
184                 d.append(r[p])
185             response_data['data'].append(d)
186         
187         return HttpResponse(json.dumps(response_data, cls=DecimalEncoder, default=DateEncoder), content_type="application/json")
188
189 def error(msg):
190     return HttpResponse(json.dumps({'error' : msg}), content_type="application/json")
191
192 def success(msg):
193     return HttpResponse(json.dumps({'success' : msg}), content_type="application/json")