| 1 |
import logging |
| 2 |
import re |
| 3 |
import warnings |
| 4 |
from inspect import getmembers, ismethod |
| 5 |
|
| 6 |
from webob import exc |
| 7 |
|
| 8 |
from .secure import handle_security, cross_boundary |
| 9 |
from .util import iscontroller, getargspec, _cfg |
| 10 |
|
| 11 |
__all__ = ['lookup_controller', 'find_object', 'route'] |
| 12 |
__observed_controllers__ = set() |
| 13 |
__custom_routes__ = {} |
| 14 |
|
| 15 |
logger = logging.getLogger(__name__) |
| 16 |
|
| 17 |
|
| 18 |
def route(*args): |
| 19 |
""" |
| 20 |
This function is used to define an explicit route for a path segment. |
| 21 |
|
| 22 |
You generally only want to use this in situations where your desired path |
| 23 |
segment is not a valid Python variable/function name. |
| 24 |
|
| 25 |
For example, if you wanted to be able to route to: |
| 26 |
|
| 27 |
/path/with-dashes/ |
| 28 |
|
| 29 |
...the following is invalid Python syntax:: |
| 30 |
|
| 31 |
class Controller(object): |
| 32 |
|
| 33 |
with-dashes = SubController() |
| 34 |
|
| 35 |
...so you would instead define the route explicitly:: |
| 36 |
|
| 37 |
class Controller(object): |
| 38 |
pass |
| 39 |
|
| 40 |
pecan.route(Controller, 'with-dashes', SubController()) |
| 41 |
""" |
| 42 |
|
| 43 |
def _validate_route(route): |
| 44 |
if not isinstance(route, str): |
| 45 |
raise TypeError('%s must be a string' % route) |
| 46 |
|
| 47 |
if route in ('.', '..') or not re.match( |
| 48 |
r'^[0-9a-zA-Z-_$\(\)\.~!,;:*+@=]+$', route |
| 49 |
): |
| 50 |
raise ValueError( |
| 51 |
'%s must be a valid path segment. Keep in mind ' |
| 52 |
'that path segments should not contain path separators ' |
| 53 |
'(e.g., /) ' % route |
| 54 |
) |
| 55 |
|
| 56 |
if len(args) == 2: |
| 57 |
# The handler in this situation is a @pecan.expose'd callable, |
| 58 |
# and is generally only used by the @expose() decorator itself. |
| 59 |
# |
| 60 |
# This sets a special attribute, `custom_route` on the callable, which |
| 61 |
# pecan's routing logic knows how to make use of (as a special case) |
| 62 |
route, handler = args |
| 63 |
if ismethod(handler): |
| 64 |
handler = handler.__func__ |
| 65 |
if not iscontroller(handler): |
| 66 |
raise TypeError( |
| 67 |
'%s must be a callable decorated with @pecan.expose' % handler |
| 68 |
) |
| 69 |
obj, attr, value = handler, 'custom_route', route |
| 70 |
|
| 71 |
if handler.__name__ in ('_lookup', '_default', '_route'): |
| 72 |
raise ValueError( |
| 73 |
'%s is a special method in pecan and cannot be used in ' |
| 74 |
'combination with custom path segments.' % handler.__name__ |
| 75 |
) |
| 76 |
elif len(args) == 3: |
| 77 |
# This is really just a setattr on the parent controller (with some |
| 78 |
# additional validation for the path segment itself) |
| 79 |
_, route, handler = args |
| 80 |
obj, attr, value = args |
| 81 |
|
| 82 |
if hasattr(obj, attr): |
| 83 |
raise RuntimeError( |
| 84 |
( |
| 85 |
"%(module)s.%(class)s already has an " |
| 86 |
"existing attribute named \"%(route)s\"." % { |
| 87 |
'module': obj.__module__, |
| 88 |
'class': obj.__name__, |
| 89 |
'route': attr |
| 90 |
} |
| 91 |
), |
| 92 |
) |
| 93 |
else: |
| 94 |
raise TypeError( |
| 95 |
'pecan.route should be called in the format ' |
| 96 |
'route(ParentController, "path-segment", SubController())' |
| 97 |
) |
| 98 |
|
| 99 |
_validate_route(route) |
| 100 |
setattr(obj, attr, value) |
| 101 |
|
| 102 |
|
| 103 |
class PecanNotFound(Exception): |
| 104 |
pass |
| 105 |
|
| 106 |
|
| 107 |
class NonCanonicalPath(Exception): |
| 108 |
''' |
| 109 |
Exception Raised when a non-canonical path is encountered when 'walking' |
| 110 |
the URI. This is typically a ``POST`` request which requires a trailing |
| 111 |
slash. |
| 112 |
''' |
| 113 |
def __init__(self, controller, remainder): |
| 114 |
self.controller = controller |
| 115 |
self.remainder = remainder |
| 116 |
|
| 117 |
|
| 118 |
def lookup_controller(obj, remainder, request=None): |
| 119 |
''' |
| 120 |
Traverses the requested url path and returns the appropriate controller |
| 121 |
object, including default routes. |
| 122 |
|
| 123 |
Handles common errors gracefully. |
| 124 |
''' |
| 125 |
if request is None: |
| 126 |
warnings.warn( |
| 127 |
( |
| 128 |
"The function signature for %s.lookup_controller is changing " |
| 129 |
"in the next version of pecan.\nPlease update to: " |
| 130 |
"`lookup_controller(self, obj, remainder, request)`." % ( |
| 131 |
__name__, |
| 132 |
) |
| 133 |
), |
| 134 |
DeprecationWarning |
| 135 |
) |
| 136 |
|
| 137 |
notfound_handlers = [] |
| 138 |
while True: |
| 139 |
try: |
| 140 |
obj, remainder = find_object(obj, remainder, notfound_handlers, |
| 141 |
request) |
| 142 |
handle_security(obj) |
| 143 |
return obj, remainder |
| 144 |
except (exc.HTTPNotFound, exc.HTTPMethodNotAllowed, |
| 145 |
PecanNotFound) as e: |
| 146 |
if isinstance(e, PecanNotFound): |
| 147 |
e = exc.HTTPNotFound() |
| 148 |
while notfound_handlers: |
| 149 |
name, obj, remainder = notfound_handlers.pop() |
| 150 |
if name == '_default': |
| 151 |
# Notfound handler is, in fact, a controller, so stop |
| 152 |
# traversal |
| 153 |
return obj, remainder |
| 154 |
else: |
| 155 |
# Notfound handler is an internal redirect, so continue |
| 156 |
# traversal |
| 157 |
result = handle_lookup_traversal(obj, remainder) |
| 158 |
if result: |
| 159 |
# If no arguments are passed to the _lookup, yet the |
| 160 |
# argspec requires at least one, raise a 404 |
| 161 |
if ( |
| 162 |
remainder == [''] and |
| 163 |
len(obj._pecan['argspec'].args) > 1 |
| 164 |
): |
| 165 |
raise e |
| 166 |
obj_, remainder_ = result |
| 167 |
return lookup_controller(obj_, remainder_, request) |
| 168 |
else: |
| 169 |
raise e |
| 170 |
|
| 171 |
|
| 172 |
def handle_lookup_traversal(obj, args): |
| 173 |
try: |
| 174 |
result = obj(*args) |
| 175 |
except TypeError as te: |
| 176 |
logger.debug('Got exception calling lookup(): %s (%s)', |
| 177 |
te, te.args) |
| 178 |
else: |
| 179 |
if result: |
| 180 |
prev_obj = obj |
| 181 |
obj, remainder = result |
| 182 |
# crossing controller boundary |
| 183 |
cross_boundary(prev_obj, obj) |
| 184 |
return result |
| 185 |
|
| 186 |
|
| 187 |
def find_object(obj, remainder, notfound_handlers, request): |
| 188 |
''' |
| 189 |
'Walks' the url path in search of an action for which a controller is |
| 190 |
implemented and returns that controller object along with what's left |
| 191 |
of the remainder. |
| 192 |
''' |
| 193 |
prev_obj = None |
| 194 |
while True: |
| 195 |
if obj is None: |
| 196 |
raise PecanNotFound |
| 197 |
if iscontroller(obj): |
| 198 |
if getattr(obj, 'custom_route', None) is None: |
| 199 |
return obj, remainder |
| 200 |
|
| 201 |
_detect_custom_path_segments(obj) |
| 202 |
|
| 203 |
if remainder: |
| 204 |
custom_route = __custom_routes__.get((obj.__class__, remainder[0])) |
| 205 |
if custom_route: |
| 206 |
return getattr(obj, custom_route), remainder[1:] |
| 207 |
|
| 208 |
# are we traversing to another controller |
| 209 |
cross_boundary(prev_obj, obj) |
| 210 |
try: |
| 211 |
next_obj, rest = remainder[0], remainder[1:] |
| 212 |
if next_obj == '': |
| 213 |
index = getattr(obj, 'index', None) |
| 214 |
if iscontroller(index): |
| 215 |
return index, rest |
| 216 |
except IndexError: |
| 217 |
# the URL has hit an index method without a trailing slash |
| 218 |
index = getattr(obj, 'index', None) |
| 219 |
if iscontroller(index): |
| 220 |
raise NonCanonicalPath(index, []) |
| 221 |
|
| 222 |
default = getattr(obj, '_default', None) |
| 223 |
if iscontroller(default): |
| 224 |
notfound_handlers.append(('_default', default, remainder)) |
| 225 |
|
| 226 |
lookup = getattr(obj, '_lookup', None) |
| 227 |
if iscontroller(lookup): |
| 228 |
notfound_handlers.append(('_lookup', lookup, remainder)) |
| 229 |
|
| 230 |
route = getattr(obj, '_route', None) |
| 231 |
if iscontroller(route): |
| 232 |
if len(getargspec(route).args) == 2: |
| 233 |
warnings.warn( |
| 234 |
( |
| 235 |
"The function signature for %s.%s._route is changing " |
| 236 |
"in the next version of pecan.\nPlease update to: " |
| 237 |
"`def _route(self, args, request)`." % ( |
| 238 |
obj.__class__.__module__, |
| 239 |
obj.__class__.__name__ |
| 240 |
) |
| 241 |
), |
| 242 |
DeprecationWarning |
| 243 |
) |
| 244 |
next_obj, next_remainder = route(remainder) |
| 245 |
else: |
| 246 |
next_obj, next_remainder = route(remainder, request) |
| 247 |
cross_boundary(route, next_obj) |
| 248 |
return next_obj, next_remainder |
| 249 |
|
| 250 |
if not remainder: |
| 251 |
raise PecanNotFound |
| 252 |
|
| 253 |
prev_remainder = remainder |
| 254 |
prev_obj = obj |
| 255 |
remainder = rest |
| 256 |
try: |
| 257 |
obj = getattr(obj, next_obj, None) |
| 258 |
except UnicodeEncodeError: |
| 259 |
obj = None |
| 260 |
|
| 261 |
# Last-ditch effort: if there's not a matching subcontroller, no |
| 262 |
# `_default`, no `_lookup`, and no `_route`, look to see if there's |
| 263 |
# an `index` that has a generic method defined for the current request |
| 264 |
# method. |
| 265 |
if not obj and not notfound_handlers and hasattr(prev_obj, 'index'): |
| 266 |
if request.method in _cfg(prev_obj.index).get('generic_handlers', |
| 267 |
{}): |
| 268 |
return prev_obj.index, prev_remainder |
| 269 |
|
| 270 |
|
| 271 |
def _detect_custom_path_segments(obj): |
| 272 |
# Detect custom controller routes (on the initial traversal) |
| 273 |
if obj.__class__.__module__ == '__builtin__': |
| 274 |
return |
| 275 |
|
| 276 |
attrs = set(dir(obj)) |
| 277 |
|
| 278 |
if obj.__class__ not in __observed_controllers__: |
| 279 |
for key, val in getmembers(obj): |
| 280 |
if iscontroller(val) and isinstance( |
| 281 |
getattr(val, 'custom_route', None), |
| 282 |
str, |
| 283 |
): |
| 284 |
route = val.custom_route |
| 285 |
|
| 286 |
# Detect class attribute name conflicts |
| 287 |
for conflict in attrs.intersection(set((route,))): |
| 288 |
raise RuntimeError( |
| 289 |
( |
| 290 |
"%(module)s.%(class)s.%(function)s has " |
| 291 |
"a custom path segment, \"%(route)s\", " |
| 292 |
"but %(module)s.%(class)s already has an " |
| 293 |
"existing attribute named \"%(route)s\"." % { |
| 294 |
'module': obj.__class__.__module__, |
| 295 |
'class': obj.__class__.__name__, |
| 296 |
'function': val.__name__, |
| 297 |
'route': conflict |
| 298 |
} |
| 299 |
), |
| 300 |
) |
| 301 |
|
| 302 |
existing = __custom_routes__.get( |
| 303 |
(obj.__class__, route) |
| 304 |
) |
| 305 |
if existing: |
| 306 |
# Detect custom path conflicts between functions |
| 307 |
raise RuntimeError( |
| 308 |
( |
| 309 |
"%(module)s.%(class)s.%(function)s and " |
| 310 |
"%(module)s.%(class)s.%(other)s have a " |
| 311 |
"conflicting custom path segment, " |
| 312 |
"\"%(route)s\"." % { |
| 313 |
'module': obj.__class__.__module__, |
| 314 |
'class': obj.__class__.__name__, |
| 315 |
'function': val.__name__, |
| 316 |
'other': existing, |
| 317 |
'route': route |
| 318 |
} |
| 319 |
), |
| 320 |
) |
| 321 |
|
| 322 |
__custom_routes__[ |
| 323 |
(obj.__class__, route) |
| 324 |
] = key |
| 325 |
__observed_controllers__.add(obj.__class__) |