Debian Codegraph @

pecan/rest.py

raw
1 from inspect import ismethod, getmembers
2 import warnings
3
4 from webob import exc
5
6 from .core import abort
7 from .decorators import expose
8 from .routing import lookup_controller, handle_lookup_traversal
9 from .util import iscontroller, getargspec
10
11
12 class RestController(object):
13 '''
14 A base class for ``REST`` based controllers. Inherit from this class
15 to implement a REST controller.
16
17 ``RestController`` implements a set of routing functions which override
18 the default pecan routing with behavior consistent with RESTful routing.
19 This functionality covers navigation to the requested resource
20 controllers, and the appropriate handling of both the common (``GET``,
21 ``POST``, ``PUT``, ``DELETE``) as well as custom-defined REST action
22 methods.
23
24 For more on developing **RESTful** web applications with Pecan, see
25 :ref:`rest`.
26 '''
27 _custom_actions = {}
28
29 def __new__(cls, *args, **kwargs):
30 """
31 RestController does not support the `route` argument to
32 :func:`~pecan.decorators.expose`
33
34 Implement this with __new__ rather than a metaclass, because it's very
35 common for pecan users to mixin RestController (with other bases that
36 have their own metaclasses).
37 """
38 for name, value in getmembers(cls):
39 if iscontroller(value) and getattr(value, 'custom_route', None):
40 raise ValueError(
41 'Path segments cannot be used in combination with '
42 'pecan.rest.RestController. Remove the `route` argument '
43 'to @pecan.expose on %s.%s.%s' % (
44 cls.__module__, cls.__name__, value.__name__
45 )
46 )
47
48 # object.__new__ will error if called with extra arguments, and either
49 # __new__ is overridden or __init__ is not overridden;
50 # https://hg.python.org/cpython/file/78d36d54391c/Objects/typeobject.c#l3034
51 # In PY3, this is a TypeError
52 new = super(RestController, cls).__new__
53 if new is object.__new__:
54 return new(cls)
55 return new(cls, *args, **kwargs)
56
57 def _get_args_for_controller(self, controller):
58 """
59 Retrieve the arguments we actually care about. For Pecan applications
60 that utilize thread locals, we should truncate the first argument,
61 `self`. For applications that explicitly pass request/response
62 references as the first controller arguments, we should truncate the
63 first three arguments, `self, req, resp`.
64 """
65 argspec = getargspec(controller)
66 from pecan import request
67 try:
68 request.path
69 except AttributeError:
70 return argspec.args[3:]
71 return argspec.args[1:]
72
73 def _handle_bad_rest_arguments(self, controller, remainder, request):
74 """
75 Ensure that the argspec for a discovered controller actually matched
76 the positional arguments in the request path. If not, raise
77 a webob.exc.HTTPBadRequest.
78 """
79 argspec = self._get_args_for_controller(controller)
80 fixed_args = len(argspec) - len(
81 request.pecan.get('routing_args', [])
82 )
83 if len(remainder) < fixed_args:
84 # For controllers that are missing intermediate IDs
85 # (e.g., /authors/books vs /authors/1/books), return a 404 for an
86 # invalid path.
87 abort(404)
88
89 def _lookup_child(self, remainder):
90 """
91 Lookup a child controller with a named path (handling Unicode paths
92 properly for Python 2).
93 """
94 try:
95 controller = getattr(self, remainder, None)
96 except UnicodeEncodeError:
97 return None
98 return controller
99
100 @expose()
101 def _route(self, args, request=None):
102 '''
103 Routes a request to the appropriate controller and returns its result.
104
105 Performs a bit of validation - refuses to route delete and put actions
106 via a GET request).
107 '''
108 if request is None:
109 from pecan import request
110 # convention uses "_method" to handle browser-unsupported methods
111 method = request.params.get('_method', request.method).lower()
112
113 # make sure DELETE/PUT requests don't use GET
114 if request.method == 'GET' and method in ('delete', 'put'):
115 abort(405)
116
117 # check for nested controllers
118 result = self._find_sub_controllers(args, request)
119 if result:
120 return result
121
122 # handle the request
123 handler = getattr(
124 self,
125 '_handle_%s' % method,
126 self._handle_unknown_method
127 )
128
129 try:
130 if len(getargspec(handler).args) == 3:
131 result = handler(method, args)
132 else:
133 result = handler(method, args, request)
134
135 #
136 # If the signature of the handler does not match the number
137 # of remaining positional arguments, attempt to handle
138 # a _lookup method (if it exists)
139 #
140 argspec = self._get_args_for_controller(result[0])
141 num_args = len(argspec)
142 if num_args < len(args):
143 _lookup_result = self._handle_lookup(args, request)
144 if _lookup_result:
145 return _lookup_result
146 except (exc.HTTPClientError, exc.HTTPNotFound,
147 exc.HTTPMethodNotAllowed) as e:
148 #
149 # If the matching handler results in a 400, 404, or 405, attempt to
150 # handle a _lookup method (if it exists)
151 #
152 _lookup_result = self._handle_lookup(args, request)
153 if _lookup_result:
154 return _lookup_result
155
156 # Build a correct Allow: header
157 if isinstance(e, exc.HTTPMethodNotAllowed):
158
159 def method_iter():
160 for func in ('get', 'get_one', 'get_all', 'new', 'edit',
161 'get_delete'):
162 if self._find_controller(func):
163 yield 'GET'
164 break
165 for method in ('HEAD', 'POST', 'PUT', 'DELETE', 'TRACE',
166 'PATCH'):
167 func = method.lower()
168 if self._find_controller(func):
169 yield method
170
171 e.allow = sorted(method_iter())
172
173 raise
174
175 # return the result
176 return result
177
178 def _handle_lookup(self, args, request=None):
179 if request is None:
180 self._raise_method_deprecation_warning(self.handle_lookup)
181
182 # filter empty strings from the arg list
183 args = list(filter(bool, args))
184
185 # check for lookup controllers
186 lookup = getattr(self, '_lookup', None)
187 if args and iscontroller(lookup):
188 result = handle_lookup_traversal(lookup, args)
189 if result:
190 obj, remainder = result
191 return lookup_controller(obj, remainder, request)
192
193 def _find_controller(self, *args):
194 '''
195 Returns the appropriate controller for routing a custom action.
196 '''
197 for name in args:
198 obj = self._lookup_child(name)
199 if obj and iscontroller(obj):
200 return obj
201 return None
202
203 def _find_sub_controllers(self, remainder, request):
204 '''
205 Identifies the correct controller to route to by analyzing the
206 request URI.
207 '''
208 # need either a get_one or get to parse args
209 method = None
210 for name in ('get_one', 'get'):
211 if hasattr(self, name):
212 method = name
213 break
214 if not method:
215 return
216
217 # get the args to figure out how much to chop off
218 args = self._get_args_for_controller(getattr(self, method))
219 fixed_args = len(args) - len(
220 request.pecan.get('routing_args', [])
221 )
222 var_args = getargspec(getattr(self, method)).varargs
223
224 # attempt to locate a sub-controller
225 if var_args:
226 for i, item in enumerate(remainder):
227 controller = self._lookup_child(item)
228 if controller and not ismethod(controller):
229 self._set_routing_args(request, remainder[:i])
230 return lookup_controller(controller, remainder[i + 1:],
231 request)
232 elif fixed_args < len(remainder) and hasattr(
233 self, remainder[fixed_args]
234 ):
235 controller = self._lookup_child(remainder[fixed_args])
236 if not ismethod(controller):
237 self._set_routing_args(request, remainder[:fixed_args])
238 return lookup_controller(
239 controller,
240 remainder[fixed_args + 1:],
241 request
242 )
243
244 def _handle_unknown_method(self, method, remainder, request=None):
245 '''
246 Routes undefined actions (like TRACE) to the appropriate controller.
247 '''
248 if request is None:
249 self._raise_method_deprecation_warning(self._handle_unknown_method)
250
251 # try finding a post_{custom} or {custom} method first
252 controller = self._find_controller('post_%s' % method, method)
253 if controller:
254 return controller, remainder
255
256 # if no controller exists, try routing to a sub-controller; note that
257 # since this isn't a safe GET verb, any local exposes are 405'd
258 if remainder:
259 if self._find_controller(remainder[0]):
260 abort(405)
261 sub_controller = self._lookup_child(remainder[0])
262 if sub_controller:
263 return lookup_controller(sub_controller, remainder[1:],
264 request)
265
266 abort(405)
267
268 def _handle_get(self, method, remainder, request=None):
269 '''
270 Routes ``GET`` actions to the appropriate controller.
271 '''
272 if request is None:
273 self._raise_method_deprecation_warning(self._handle_get)
274
275 # route to a get_all or get if no additional parts are available
276 if not remainder or remainder == ['']:
277 remainder = list(filter(bool, remainder))
278 controller = self._find_controller('get_all', 'get')
279 if controller:
280 self._handle_bad_rest_arguments(controller, remainder, request)
281 return controller, []
282 abort(405)
283
284 method_name = remainder[-1]
285 # check for new/edit/delete GET requests
286 if method_name in ('new', 'edit', 'delete'):
287 if method_name == 'delete':
288 method_name = 'get_delete'
289 controller = self._find_controller(method_name)
290 if controller:
291 return controller, remainder[:-1]
292
293 match = self._handle_custom_action(method, remainder, request)
294 if match:
295 return match
296
297 controller = self._lookup_child(remainder[0])
298 if controller and not ismethod(controller):
299 return lookup_controller(controller, remainder[1:], request)
300
301 # finally, check for the regular get_one/get requests
302 controller = self._find_controller('get_one', 'get')
303 if controller:
304 self._handle_bad_rest_arguments(controller, remainder, request)
305 return controller, remainder
306
307 abort(405)
308
309 def _handle_delete(self, method, remainder, request=None):
310 '''
311 Routes ``DELETE`` actions to the appropriate controller.
312 '''
313 if request is None:
314 self._raise_method_deprecation_warning(self._handle_delete)
315
316 if remainder:
317 match = self._handle_custom_action(method, remainder, request)
318 if match:
319 return match
320
321 controller = self._lookup_child(remainder[0])
322 if controller and not ismethod(controller):
323 return lookup_controller(controller, remainder[1:], request)
324
325 # check for post_delete/delete requests first
326 controller = self._find_controller('post_delete', 'delete')
327 if controller:
328 return controller, remainder
329
330 # if no controller exists, try routing to a sub-controller; note that
331 # since this is a DELETE verb, any local exposes are 405'd
332 if remainder:
333 if self._find_controller(remainder[0]):
334 abort(405)
335 sub_controller = self._lookup_child(remainder[0])
336 if sub_controller:
337 return lookup_controller(sub_controller, remainder[1:],
338 request)
339
340 abort(405)
341
342 def _handle_post(self, method, remainder, request=None):
343 '''
344 Routes ``POST`` requests.
345 '''
346 if request is None:
347 self._raise_method_deprecation_warning(self._handle_post)
348
349 # check for custom POST/PUT requests
350 if remainder:
351 match = self._handle_custom_action(method, remainder, request)
352 if match:
353 return match
354
355 controller = self._lookup_child(remainder[0])
356 if controller and not ismethod(controller):
357 return lookup_controller(controller, remainder[1:], request)
358
359 # check for regular POST/PUT requests
360 controller = self._find_controller(method)
361 if controller:
362 return controller, remainder
363
364 abort(405)
365
366 def _handle_put(self, method, remainder, request=None):
367 return self._handle_post(method, remainder, request)
368
369 def _handle_custom_action(self, method, remainder, request=None):
370 if request is None:
371 self._raise_method_deprecation_warning(self._handle_custom_action)
372
373 remainder = [r for r in remainder if r]
374 if remainder:
375 if method in ('put', 'delete'):
376 # For PUT and DELETE, additional arguments are supplied, e.g.,
377 # DELETE /foo/XYZ
378 method_name = remainder[0]
379 remainder = remainder[1:]
380 else:
381 method_name = remainder[-1]
382 remainder = remainder[:-1]
383 if method.upper() in self._custom_actions.get(method_name, []):
384 controller = self._find_controller(
385 '%s_%s' % (method, method_name),
386 method_name
387 )
388 if controller:
389 return controller, remainder
390
391 def _set_routing_args(self, request, args):
392 '''
393 Sets default routing arguments.
394 '''
395 request.pecan.setdefault('routing_args', []).extend(args)
396
397 def _raise_method_deprecation_warning(self, handler):
398 warnings.warn(
399 (
400 "The function signature for %s.%s.%s is changing "
401 "in the next version of pecan.\nPlease update to: "
402 "`%s(self, method, remainder, request)`." % (
403 self.__class__.__module__,
404 self.__class__.__name__,
405 handler.__name__,
406 handler.__name__
407 )
408 ),
409 DeprecationWarning
410 )