forked from hforge/ikaaro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrest.py
294 lines (225 loc) · 8.38 KB
/
rest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# -*- coding: UTF-8 -*-
# Copyright (C) 2011 Juan David Ibáñez Palomar <[email protected]>
# Copyright (C) 2011 Hervé Cauwelier <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import from the Standard Library
from base64 import b64encode, b64decode
import json
# Import from itools
from itools.core import proto_lazy_property
from itools.database import AndQuery, PhraseQuery
from itools.handlers import checkid
from itools.web import BaseView
# Import from ikaaro
from fields import Metadata_Field, File_Field
from resource_views import LoginView
from utils import get_base_path_query
###########################################################################
# Utility functions
###########################################################################
def fix_json(obj):
"""Utility function, given a json object as returned by json.loads
transform the unicode strings to strings.
TODO Use a custom JSONDecoder instead.
"""
obj_type = type(obj)
if obj_type is unicode:
return obj.encode('utf-8')
if obj_type is list:
return [ fix_json(x) for x in obj ]
if obj_type is dict:
aux = {}
for x, y in obj.items():
aux[fix_json(x)] = fix_json(y)
return aux
return obj
def update_resource(resource, changes):
for name, value, parameters in changes:
# The value
field = resource.get_field(name)
if field is None:
raise ValueError, "undefined field '%s'" % name
if not field.access('write', resource):
continue # XXX raise an error? log a message?
if issubclass(field, File_Field):
value = b64decode(value)
else:
datatype = field.get_datatype()
value = datatype.decode(value)
# The language
lang = parameters.pop('lang', None)
# Decode parameters
for pname, pvalue in parameters.items():
parameters[pname] = field.parameters_schema[pname].decode(pvalue)
# Action
resource.set_value(name, value, lang, **parameters)
def property_to_json(field, prop):
# The value
value = field.get_datatype().encode(prop.value)
value = {'value': value}
# The parameters
if not prop.parameters:
return value
for name, datatype in field.parameters_schema.items():
param_value = prop.parameters.get(name)
if param_value is not None:
value[name] = datatype.encode(param_value)
return value
def field_to_json(resource, field_name):
field = resource.get_field(field_name)
if field is None:
return None
if not field.access('read', resource):
return None
# Metadata
if issubclass(field, Metadata_Field):
prop = resource.metadata.properties.get(field_name)
if prop is None:
return None
if type(prop) is dict:
prop = prop.values()
if type(prop) is list:
return [ property_to_json(field, x) for x in prop ]
return property_to_json(field, prop)
# Files
if issubclass(field, File_Field):
handler = field.get_value(resource, field_name)
if not handler:
return None
return {'value': b64encode(handler.to_str())}
# Computed
value = field.get_value(resource, field_name)
return {'value': value}
###########################################################################
# Login
###########################################################################
class Rest_Login(LoginView):
def POST(self, resource, context):
super(Rest_Login, self).POST(resource, context)
# Failed
user = context.user
if user is None:
return None
# Ok
context.set_content_type('text/plain')
return str(user.abspath)
###########################################################################
# The CRUD Views
###########################################################################
class Rest_BaseView(BaseView):
"""Base class for other for the RESTful interface.
"""
def return_json(self, data):
self.context.set_content_type('application/json')
return json.dumps(data)
@proto_lazy_property
def json(self):
"""Utility method that loads the json from the request entity. Used
by POST and PUT request methods.
"""
data = self.context.body['body']
data = json.loads(data) # TODO Use a custom JSONDecoder
return fix_json(data)
def created(self, resource):
context = self.context
path = resource.abspath
context.status = 201
context.set_header('Location', str(context.uri.resolve(path)))
context.set_content_type('text/plain')
return str(path)
class Rest_Read(Rest_BaseView):
"""The R of CRUD: READ
"""
access = 'is_allowed_to_view'
def GET(self, resource, context):
# Build a dictionary represeting the resource by its schema.
representation = {}
representation['format'] = {'value': resource.class_id}
for field_name in resource.fields:
value = field_to_json(resource, field_name)
if value is not None:
representation[field_name] = value
# Set last modification time
mtime = resource.get_value('mtime')
context.set_header('Last-Modified', mtime)
# Ok
return self.return_json(representation)
class Rest_Create(Rest_BaseView):
"""The C of CRUD: CREATE
"""
access = 'is_allowed_to_add'
def POST(self, resource, context):
name, class_id, changes = self.json
# 1. Make the resource
if name is not None:
name = checkid(name)
cls = context.database.get_resource_class(class_id)
child = resource.make_resource(name, cls)
# 2. Modify the resource
update_resource(child, changes)
# 3. Return the URL of the new resource
return self.created(child)
class Rest_Update(Rest_BaseView):
"""The U of CRUD: UPDATE
"""
access = 'is_allowed_to_edit'
def POST(self, resource, context):
changes = self.json
update_resource(resource, changes)
# Empty 200 OK
context.set_content_type('text/plain')
return ''
class Rest_Delete(Rest_BaseView):
"""The D of CRUD: DELETE
"""
access = 'is_allowed_to_remove'
def POST(self, resource, context):
"""The D of CRUD: DELETE
"""
# Delete myself
resource.parent.del_resource(resource.name)
# None means 204
return None
###########################################################################
# Other views
###########################################################################
class Rest_Query(Rest_BaseView):
access = 'is_allowed_to_view'
def GET(self, resource, context):
# Build the query
query = get_base_path_query(resource.abspath)
for key, value in context.uri.query.items():
if key == 'abspath' and value == 'myself':
value = str(context.user.abspath)
query = AndQuery(query, PhraseQuery(key, value))
# Search
items = []
for resource in context.search(query).get_resources():
item = {'abspath': {'value': str(resource.abspath)}}
for field_name in resource.fields:
value = field_to_json(resource, field_name)
if value is not None:
item[field_name] = value
items.append(item)
# Ok
return self.return_json(items)
class Rest_Schema(Rest_BaseView):
access = 'is_allowed_to_view'
def GET(self, resource, context):
schema = {}
for name, field in resource.get_fields():
schema[name] = field.rest()
# Ok
return self.return_json(schema)