-
Notifications
You must be signed in to change notification settings - Fork 2
/
tubes.py
353 lines (285 loc) · 11.9 KB
/
tubes.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
'''module to create REST APIS'''
import os
import re
import functools
try:
import json
except ImportError:
import simplejson as json
import werkzeug
from werkzeug import Request
from werkzeug import Response
from werkzeug import redirect
# http://www.sfsu.edu/training/mimetype.htm
BIN = 'application/octet-stream'
JSON = 'application/json'
TEXT = 'text/plain'
HTML = 'text/html'
XML = 'text/xml'
JS = 'application/javascript'
ATOM = 'application/atom+xml'
ICON = 'image/vnd.microsoft.icon'
PDF = 'application/pdf'
RTF = 'application/rtf'
PNG = 'image/png'
JQUERY_TYPES = {}
JQUERY_TYPES[JSON] = 'json'
JQUERY_TYPES[TEXT] = 'text'
JQUERY_TYPES[HTML] = 'html'
JQUERY_TYPES[XML] = 'xml'
class Route(object):
'''a class that represents a registered route'''
def __init__(self, pattern, handler, accepts=None, produces=TEXT,
has_payload=False, transform_body=None):
'''pattern -- the regex that when matches calls handler
handler -- the method to call when pattern matches
accepts -- the content type that is accepted
produces -- the content type that handler produces
has_payload -- if the request contains information on the body
transform_body -- if accepts is JSON then call the method in this
attribute and use the returned value as parameter to the method that
handles the request
'''
self.pattern = pattern
self.regex = re.compile(pattern)
self.group_count = pattern.count('(')
self.handler = handler
self.accepts = accepts
self.produces = produces
self.has_payload = has_payload
self.transform_body = transform_body
def generate_route_decorator(method):
'''return a decorator that will add Route objects to method'''
def decorator(self, pattern, accepts=None, produces=JSON, has_payload=False,
transform_body=None):
'''the decorator to register a new Route'''
def wrapper(func):
'''the decorator itself'''
self.register_route(method, pattern, func, accepts, produces,
has_payload, transform_body)
return func
return wrapper
return decorator
class Handler(object):
'''handler for requests'''
__name__ = 'tubes'
def __init__(self):
self.routes = {}
self.marshallers = {JSON: json.dumps}
self.static_paths = {}
def __call__(self, environ, start_response):
'''try to match the request with the registered routes'''
path = environ.get('PATH_INFO', '')
command = environ.get('REQUEST_METHOD', None)
request = Request(environ)
for route in self.routes.get(command, ()):
accepts = request.accept_mimetypes.values()
if route.accepts and request.accept_mimetypes and \
route.accepts not in accepts and '*/*' not in accepts:
continue
match = route.regex.match(path)
if match is not None:
if route.group_count == 0:
args = []
elif route.group_count == 1:
args = [match.group(1)]
else:
args = match.group(*range(1, route.group_count + 1))
if route.accepts == JSON:
data = json.loads(request.stream.read())
if route.transform_body is not None:
data = route.transform_body(data)
# add the body of the request as first parameter
args.insert(0, data)
try:
result = route.handler(request, *args)
except Response, response:
return response
if isinstance(result, werkzeug.BaseResponse):
return result(environ, start_response)
if route.produces == JSON and is_json_class(result):
result = result.to_json_str()
elif route.produces in self.marshallers:
result = self.marshallers[route.produces](result)
return Response(result, content_type=route.produces)(environ,
start_response)
return Response(status=404)(environ, start_response)
def register_route(self, method, pattern, handler, accepts, produces,
has_payload, transform_body):
'''register a new route on the routes class variable'''
if method not in self.routes:
self.routes[method] = []
self.routes[method].append(Route(pattern, handler, accepts, produces,
has_payload, transform_body))
def register_marshaller(self, mimetype, func):
'''register a method to transform an input to an output accourding
to the mimetype '''
self.marshallers[mimetype] = func
def register_static_path(self, match_path, *dest_path):
'''register a path that will be served as static content'''
self.static_paths[match_path] = os.path.join(*dest_path)
def authorize(self, authorize_func):
'''decorator to validate a request prior to calling the handler
if the authorize_func returns True, them the function is called
otherwise 401 is returned
'''
def wrapper(func):
@functools.wraps(func)
def inner(*args, **kwargs):
if authorize_func(args[0]):
return func(*args, **kwargs)
else:
return Response("unauthorized", 401)
return inner
return wrapper
# http://tools.ietf.org/html/rfc2616#page-51
get = generate_route_decorator('GET')
post = generate_route_decorator('POST')
put = generate_route_decorator('PUT')
delete = generate_route_decorator('DELETE')
options = generate_route_decorator('OPTIONS')
head = generate_route_decorator('HEAD')
trace = generate_route_decorator('TRACE')
connect = generate_route_decorator('CONNECT')
class JsonClass(object):
'''a class decorator to allow transformations to and from JSON
'''
def __init__(self, to_ignore=None, from_ignore=None,
to_transform=None, from_transform=None, exclude_private_fields=True):
'''constructor
to_ignore -- a list of attributes to ignore when transforming to json
from_ignore -- a list of attributes to ignore when transforming form json
to_transform -- a dict with name atributes as keys and a callable as value
that will be called with the name and the value of the attr and
should return the transformed name and value to be used for
marshaling
from_transform -- idem to to_trasnform but used with input values to
transform
'''
self.to_ignore = to_ignore
if self.to_ignore is None:
self.to_ignore = []
self.from_ignore = from_ignore
if self.from_ignore is None:
self.from_ignore = []
self.to_transform = to_transform
if self.to_transform is None:
self.to_transform = {}
self.from_transform = from_transform
if self.from_transform is None:
self.from_transform = {}
self.exclude_private_fields = exclude_private_fields
def __call__(self, cls):
'''the decorator, add constants to the class:
* cls.TUBES_JSON_SERIALIZABLE = True
and class methods:
* cls.from_json()
* cls.from_json_str()
and instance methods:
* cls.to_json()
* cls.to_json_str()
'''
if hasattr(cls, 'TUBES_JSON_SERIALIZABLE'):
return cls
setattr(cls, 'from_json', classmethod(from_json))
setattr(cls, 'from_json_str', classmethod(from_json_str))
setattr(cls, 'to_json', to_json)
setattr(cls, 'to_json_str', to_json_str)
setattr(cls, 'to_json_list', classmethod(to_json_list))
setattr(cls, 'to_json_list_str', classmethod(to_json_list_str))
setattr(cls, 'TUBES_JSON_SERIALIZABLE', True)
setattr(cls, 'TUBES_TO_IGNORE', self.to_ignore)
setattr(cls, 'TUBES_FROM_IGNORE', self.from_ignore)
setattr(cls, 'TUBES_TO_TRANSFORM', self.to_transform)
setattr(cls, 'TUBES_FROM_TRANSFORM', self.from_transform)
setattr(cls, 'TUBES_EXCLUDE_PRIVATE_FIELDS',
self.exclude_private_fields)
return cls
def is_json_class(cls):
'''return True if cls is a json class
'''
return hasattr(cls, 'TUBES_JSON_SERIALIZABLE')
def from_json(cls, obj):
'''return a class instance taking the values from the json obj and
transforming according to from_transform
'''
instance = cls()
for name, value in obj.iteritems():
if name in cls.TUBES_FROM_IGNORE:
continue
if name in cls.TUBES_FROM_TRANSFORM:
name, value = cls.TUBES_FROM_TRANSFORM[name](name, value)
if hasattr(instance, name):
setattr(instance, name, value)
return instance
def from_json_str(cls, obj_str):
'''return a class instance taking the values from the json str and
transforming according to from_transform
'''
return cls.from_json(json.loads(obj_str))
def to_json(self):
'''return a json representation of the object
'''
fields = []
for name, value in vars(self).iteritems():
if name in self.TUBES_TO_IGNORE:
continue
if self.TUBES_EXCLUDE_PRIVATE_FIELDS and name.startswith('_'):
continue
if name in self.TUBES_TO_TRANSFORM:
name, value = self.TUBES_TO_TRANSFORM[name](name, value)
fields.append((name, value))
return dict(fields)
def to_json_str(self):
'''return a json string representation of the object
'''
return json.dumps(self.to_json())
def to_json_list(cls, objs):
'''return a list of json objects of this class
'''
return [obj.to_json() for obj in objs]
def to_json_list_str(cls, objs):
'''return a string representing a list of json objects of this class
'''
return json.dumps(cls.to_json_list(objs))
def _replace_underscore_to_camelcase(match):
'''function used in underscores_to_camelcase to replace the match
'''
return match.group(1).upper()
def _replace_camelcase_to_underscore(match):
'''function used in camelcase_to_underscores to replace the match
'''
return "%s_%s" % (match.group(1), match.group(2).lower())
def underscores_to_camelcase(name):
'''replace all the underscores followed by a a to z letter to camelcase
'''
return re.sub('\_([a-z])', _replace_underscore_to_camelcase, name)
def camelcase_to_underscores(name):
'''replace all the [a-z] followed by [A-Z] to underscores
when something like a_b_c_d is replaced to aBCD the oposite wont be a_b_c_d
but a_bC_d
'''
return re.sub('([a-z])([A-Z])', _replace_camelcase_to_underscore, name)
def c2u(name, value):
'''utility function to be used when transforming to or from JSON
'''
return camelcase_to_underscores(name), value
def u2c(name, value):
'''utility function to be used when transforming to or from JSON
'''
return underscores_to_camelcase(name), value
def run(handler, host='0.0.0.0', port=8000, use_reloader=False,
use_debugger=False, use_evalex=True, extra_files=None,
reloader_interval=1, threaded=False, processes=1, request_handler=None,
passthrough_errors=False):
'''create a server instance and run it'''
werkzeug.run_simple(host, port, handler, use_reloader, use_debugger,
use_evalex, extra_files, reloader_interval, threaded, processes,
request_handler, handler.static_paths, passthrough_errors)
def run_gae(handler):
'''run the application on google app engine'''
if handler.static_paths:
from werkzeug.utils import SharedDataMiddleware
handler = SharedDataMiddleware(handler, handler.static_paths)
from google.appengine.ext.webapp.util import run_wsgi_app
run_wsgi_app(handler)