| 1 |
from inspect import Arguments |
| 2 |
from itertools import chain, tee |
| 3 |
from mimetypes import guess_type, add_type |
| 4 |
from os.path import splitext |
| 5 |
import logging |
| 6 |
import operator |
| 7 |
import sys |
| 8 |
import types |
| 9 |
|
| 10 |
from webob import (Request as WebObRequest, Response as WebObResponse, exc, |
| 11 |
acceptparse) |
| 12 |
from webob.multidict import NestedMultiDict |
| 13 |
|
| 14 |
from .compat import urlparse, izip, is_bound_method as ismethod |
| 15 |
from .jsonify import encode as dumps |
| 16 |
from .secure import handle_security |
| 17 |
from .templating import RendererFactory |
| 18 |
from .routing import lookup_controller, NonCanonicalPath |
| 19 |
from .util import _cfg, getargspec |
| 20 |
from .middleware.recursive import ForwardRequestException |
| 21 |
|
| 22 |
|
| 23 |
# make sure that json is defined in mimetypes |
| 24 |
add_type('application/json', '.json', True) |
| 25 |
|
| 26 |
state = None |
| 27 |
logger = logging.getLogger(__name__) |
| 28 |
|
| 29 |
|
| 30 |
class RoutingState(object): |
| 31 |
|
| 32 |
def __init__(self, request, response, app, hooks=None, controller=None, |
| 33 |
arguments=None): |
| 34 |
self.request = request |
| 35 |
self.response = response |
| 36 |
self.app = app |
| 37 |
self.hooks = hooks or [] |
| 38 |
self.controller = controller |
| 39 |
self.arguments = arguments |
| 40 |
|
| 41 |
|
| 42 |
class Request(WebObRequest): |
| 43 |
|
| 44 |
def __getattribute__(self, name): |
| 45 |
try: |
| 46 |
return WebObRequest.__getattribute__(self, name) |
| 47 |
except UnicodeDecodeError as e: |
| 48 |
logger.exception(e) |
| 49 |
abort(400) |
| 50 |
|
| 51 |
|
| 52 |
class Response(WebObResponse): |
| 53 |
pass |
| 54 |
|
| 55 |
|
| 56 |
def proxy(key): |
| 57 |
class ObjectProxy(object): |
| 58 |
|
| 59 |
explanation_ = AttributeError( |
| 60 |
"`pecan.state` is not bound to a context-local context.\n" |
| 61 |
"Ensure that you're accessing `pecan.request` or `pecan.response` " |
| 62 |
"from within the context of a WSGI `__call__` and that " |
| 63 |
"`use_context_locals` = True." |
| 64 |
) |
| 65 |
|
| 66 |
def __getattr__(self, attr): |
| 67 |
try: |
| 68 |
obj = getattr(state, key) |
| 69 |
except AttributeError: |
| 70 |
raise self.explanation_ |
| 71 |
return getattr(obj, attr) |
| 72 |
|
| 73 |
def __setattr__(self, attr, value): |
| 74 |
obj = getattr(state, key) |
| 75 |
return setattr(obj, attr, value) |
| 76 |
|
| 77 |
def __delattr__(self, attr): |
| 78 |
obj = getattr(state, key) |
| 79 |
return delattr(obj, attr) |
| 80 |
|
| 81 |
def __dir__(self): |
| 82 |
obj = getattr(state, key) |
| 83 |
return dir(obj) |
| 84 |
|
| 85 |
return ObjectProxy() |
| 86 |
|
| 87 |
|
| 88 |
request = proxy('request') |
| 89 |
response = proxy('response') |
| 90 |
|
| 91 |
|
| 92 |
def override_template(template, content_type=None): |
| 93 |
''' |
| 94 |
Call within a controller to override the template that is used in |
| 95 |
your response. |
| 96 |
|
| 97 |
:param template: a valid path to a template file, just as you would specify |
| 98 |
in an ``@expose``. |
| 99 |
:param content_type: a valid MIME type to use for the response.func_closure |
| 100 |
''' |
| 101 |
|
| 102 |
request.pecan['override_template'] = template |
| 103 |
if content_type: |
| 104 |
request.pecan['override_content_type'] = content_type |
| 105 |
|
| 106 |
|
| 107 |
def abort(status_code, detail='', headers=None, comment=None, **kw): |
| 108 |
''' |
| 109 |
Raise an HTTP status code, as specified. Useful for returning status |
| 110 |
codes like 401 Unauthorized or 403 Forbidden. |
| 111 |
|
| 112 |
:param status_code: The HTTP status code as an integer. |
| 113 |
:param detail: The message to send along, as a string. |
| 114 |
:param headers: A dictionary of headers to send along with the response. |
| 115 |
:param comment: A comment to include in the response. |
| 116 |
''' |
| 117 |
|
| 118 |
# If there is a traceback, we need to catch it for a re-raise |
| 119 |
try: |
| 120 |
_, _, traceback = sys.exc_info() |
| 121 |
webob_exception = exc.status_map[status_code]( |
| 122 |
detail=detail, |
| 123 |
headers=headers, |
| 124 |
comment=comment, |
| 125 |
**kw |
| 126 |
) |
| 127 |
raise webob_exception.with_traceback(traceback) |
| 128 |
finally: |
| 129 |
# Per the suggestion of the Python docs, delete the traceback object |
| 130 |
del traceback |
| 131 |
|
| 132 |
|
| 133 |
def redirect(location=None, internal=False, code=None, headers=None, |
| 134 |
add_slash=False, request=None): |
| 135 |
''' |
| 136 |
Perform a redirect, either internal or external. An internal redirect |
| 137 |
performs the redirect server-side, while the external redirect utilizes |
| 138 |
an HTTP 302 status code. |
| 139 |
|
| 140 |
:param location: The HTTP location to redirect to. |
| 141 |
:param internal: A boolean indicating whether the redirect should be |
| 142 |
internal. |
| 143 |
:param code: The HTTP status code to use for the redirect. Defaults to 302. |
| 144 |
:param headers: Any HTTP headers to send with the response, as a |
| 145 |
dictionary. |
| 146 |
:param request: The :class:`pecan.Request` instance to use. |
| 147 |
''' |
| 148 |
request = request or state.request |
| 149 |
|
| 150 |
if add_slash: |
| 151 |
if location is None: |
| 152 |
split_url = list(urlparse.urlsplit(request.url)) |
| 153 |
new_proto = request.environ.get( |
| 154 |
'HTTP_X_FORWARDED_PROTO', split_url[0] |
| 155 |
) |
| 156 |
split_url[0] = new_proto |
| 157 |
else: |
| 158 |
split_url = urlparse.urlsplit(location) |
| 159 |
|
| 160 |
split_url[2] = split_url[2].rstrip('/') + '/' |
| 161 |
location = urlparse.urlunsplit(split_url) |
| 162 |
|
| 163 |
if not headers: |
| 164 |
headers = {} |
| 165 |
if internal: |
| 166 |
if code is not None: |
| 167 |
raise ValueError('Cannot specify a code for internal redirects') |
| 168 |
request.environ['pecan.recursive.context'] = request.context |
| 169 |
raise ForwardRequestException(location) |
| 170 |
if code is None: |
| 171 |
code = 302 |
| 172 |
raise exc.status_map[code](location=location, headers=headers) |
| 173 |
|
| 174 |
|
| 175 |
def render(template, namespace, app=None): |
| 176 |
''' |
| 177 |
Render the specified template using the Pecan rendering framework |
| 178 |
with the specified template namespace as a dictionary. Useful in a |
| 179 |
controller where you have no template specified in the ``@expose``. |
| 180 |
|
| 181 |
:param template: The path to your template, as you would specify in |
| 182 |
``@expose``. |
| 183 |
:param namespace: The namespace to use for rendering the template, as a |
| 184 |
dictionary. |
| 185 |
:param app: The instance of :class:`pecan.Pecan` to use |
| 186 |
''' |
| 187 |
app = app or state.app |
| 188 |
return app.render(template, namespace) |
| 189 |
|
| 190 |
|
| 191 |
def load_app(config, **kwargs): |
| 192 |
''' |
| 193 |
Used to load a ``Pecan`` application and its environment based on passed |
| 194 |
configuration. |
| 195 |
|
| 196 |
:param config: Can be a dictionary containing configuration, a string which |
| 197 |
represents a (relative) configuration filename |
| 198 |
|
| 199 |
returns a pecan.Pecan object |
| 200 |
''' |
| 201 |
from .configuration import _runtime_conf, set_config |
| 202 |
set_config(config, overwrite=True) |
| 203 |
|
| 204 |
for package_name in getattr(_runtime_conf.app, 'modules', []): |
| 205 |
module = __import__(package_name, fromlist=['app']) |
| 206 |
if hasattr(module, 'app') and hasattr(module.app, 'setup_app'): |
| 207 |
app = module.app.setup_app(_runtime_conf, **kwargs) |
| 208 |
app.config = _runtime_conf |
| 209 |
return app |
| 210 |
raise RuntimeError( |
| 211 |
'No app.setup_app found in any of the configured app.modules' |
| 212 |
) |
| 213 |
|
| 214 |
|
| 215 |
class PecanBase(object): |
| 216 |
|
| 217 |
SIMPLEST_CONTENT_TYPES = ( |
| 218 |
['text/html'], |
| 219 |
['text/plain'] |
| 220 |
) |
| 221 |
|
| 222 |
def __init__(self, root, default_renderer='mako', |
| 223 |
template_path='templates', hooks=lambda: [], |
| 224 |
custom_renderers=None, extra_template_vars=None, |
| 225 |
force_canonical=True, guess_content_type_from_ext=True, |
| 226 |
context_local_factory=None, request_cls=Request, |
| 227 |
response_cls=Response, **kw): |
| 228 |
if isinstance(root, str): |
| 229 |
root = self.__translate_root__(root) |
| 230 |
|
| 231 |
self.root = root |
| 232 |
self.request_cls = request_cls |
| 233 |
self.response_cls = response_cls |
| 234 |
self.renderers = RendererFactory(custom_renderers, extra_template_vars) |
| 235 |
self.default_renderer = default_renderer |
| 236 |
|
| 237 |
# pre-sort these so we don't have to do it per-request |
| 238 |
if callable(hooks): |
| 239 |
hooks = hooks() |
| 240 |
|
| 241 |
self.hooks = list(sorted( |
| 242 |
hooks, |
| 243 |
key=operator.attrgetter('priority') |
| 244 |
)) |
| 245 |
self.template_path = template_path |
| 246 |
self.force_canonical = force_canonical |
| 247 |
self.guess_content_type_from_ext = guess_content_type_from_ext |
| 248 |
|
| 249 |
def __translate_root__(self, item): |
| 250 |
''' |
| 251 |
Creates a root controller instance from a string root, e.g., |
| 252 |
|
| 253 |
> __translate_root__("myproject.controllers.RootController") |
| 254 |
myproject.controllers.RootController() |
| 255 |
|
| 256 |
:param item: The string to the item |
| 257 |
''' |
| 258 |
|
| 259 |
if '.' in item: |
| 260 |
parts = item.split('.') |
| 261 |
name = '.'.join(parts[:-1]) |
| 262 |
fromlist = parts[-1:] |
| 263 |
|
| 264 |
module = __import__(name, fromlist=fromlist) |
| 265 |
kallable = getattr(module, parts[-1]) |
| 266 |
msg = "%s does not represent a callable class or function." |
| 267 |
if not callable(kallable): |
| 268 |
raise TypeError(msg % item) |
| 269 |
return kallable() |
| 270 |
|
| 271 |
raise ImportError('No item named %s' % item) |
| 272 |
|
| 273 |
def route(self, req, node, path): |
| 274 |
''' |
| 275 |
Looks up a controller from a node based upon the specified path. |
| 276 |
|
| 277 |
:param node: The node, such as a root controller object. |
| 278 |
:param path: The path to look up on this node. |
| 279 |
''' |
| 280 |
path = path.split('/')[1:] |
| 281 |
try: |
| 282 |
node, remainder = lookup_controller(node, path, req) |
| 283 |
return node, remainder |
| 284 |
except NonCanonicalPath as e: |
| 285 |
if self.force_canonical and \ |
| 286 |
not _cfg(e.controller).get('accept_noncanonical', False): |
| 287 |
if req.method == 'POST': |
| 288 |
raise RuntimeError( |
| 289 |
"You have POSTed to a URL '%s' which " |
| 290 |
"requires a slash. Most browsers will not maintain " |
| 291 |
"POST data when redirected. Please update your code " |
| 292 |
"to POST to '%s/' or set force_canonical to False" % |
| 293 |
(req.pecan['routing_path'], |
| 294 |
req.pecan['routing_path']) |
| 295 |
) |
| 296 |
redirect(code=302, add_slash=True, request=req) |
| 297 |
return e.controller, e.remainder |
| 298 |
|
| 299 |
def determine_hooks(self, controller=None): |
| 300 |
''' |
| 301 |
Determines the hooks to be run, in which order. |
| 302 |
|
| 303 |
:param controller: If specified, includes hooks for a specific |
| 304 |
controller. |
| 305 |
''' |
| 306 |
|
| 307 |
controller_hooks = [] |
| 308 |
if controller: |
| 309 |
controller_hooks = _cfg(controller).get('hooks', []) |
| 310 |
if controller_hooks: |
| 311 |
return list( |
| 312 |
sorted( |
| 313 |
chain(controller_hooks, self.hooks), |
| 314 |
key=operator.attrgetter('priority') |
| 315 |
) |
| 316 |
) |
| 317 |
return self.hooks |
| 318 |
|
| 319 |
def handle_hooks(self, hooks, hook_type, *args): |
| •320 |
r''' |
| 321 |
Processes hooks of the specified type. |
| 322 |
|
| 323 |
:param hook_type: The type of hook, including ``before``, ``after``, |
| 324 |
``on_error``, and ``on_route``. |
| 325 |
:param *args: Arguments to pass to the hooks. |
| 326 |
''' |
| 327 |
if hook_type not in ['before', 'on_route']: |
| 328 |
hooks = reversed(hooks) |
| 329 |
|
| 330 |
for hook in hooks: |
| 331 |
result = getattr(hook, hook_type)(*args) |
| 332 |
# on_error hooks can choose to return a Response, which will |
| 333 |
# be used instead of the standard error pages. |
| 334 |
if hook_type == 'on_error' and isinstance(result, WebObResponse): |
| 335 |
return result |
| 336 |
|
| 337 |
def get_args(self, state, all_params, remainder, argspec, im_self): |
| 338 |
''' |
| 339 |
Determines the arguments for a controller based upon parameters |
| 340 |
passed the argument specification for the controller. |
| 341 |
''' |
| 342 |
args = [] |
| 343 |
varargs = [] |
| 344 |
kwargs = dict() |
| 345 |
valid_args = argspec.args[:] |
| 346 |
if ismethod(state.controller) or im_self: |
| 347 |
valid_args.pop(0) # pop off `self` |
| 348 |
pecan_state = state.request.pecan |
| 349 |
|
| 350 |
remainder = [x for x in remainder if x] |
| 351 |
|
| 352 |
if im_self is not None: |
| 353 |
args.append(im_self) |
| 354 |
|
| 355 |
# grab the routing args from nested REST controllers |
| 356 |
if 'routing_args' in pecan_state: |
| 357 |
remainder = pecan_state['routing_args'] + list(remainder) |
| 358 |
del pecan_state['routing_args'] |
| 359 |
|
| 360 |
# handle positional arguments |
| 361 |
if valid_args and remainder: |
| 362 |
args.extend(remainder[:len(valid_args)]) |
| 363 |
remainder = remainder[len(valid_args):] |
| 364 |
valid_args = valid_args[len(args):] |
| 365 |
|
| 366 |
# handle wildcard arguments |
| 367 |
if [i for i in remainder if i]: |
| 368 |
if not argspec[1]: |
| 369 |
abort(404) |
| 370 |
varargs.extend(remainder) |
| 371 |
|
| 372 |
# get the default positional arguments |
| 373 |
if argspec[3]: |
| 374 |
defaults = dict(izip(argspec[0][-len(argspec[3]):], argspec[3])) |
| 375 |
else: |
| 376 |
defaults = dict() |
| 377 |
|
| 378 |
# handle positional GET/POST params |
| 379 |
for name in valid_args: |
| 380 |
if name in all_params: |
| 381 |
args.append(all_params.pop(name)) |
| 382 |
elif name in defaults: |
| 383 |
args.append(defaults[name]) |
| 384 |
else: |
| 385 |
break |
| 386 |
|
| 387 |
# handle wildcard GET/POST params |
| 388 |
if argspec[2]: |
| 389 |
for name, value in iter(all_params.items()): |
| 390 |
if name not in argspec[0]: |
| 391 |
kwargs[name] = value |
| 392 |
|
| 393 |
return args, varargs, kwargs |
| 394 |
|
| 395 |
def render(self, template, namespace): |
| 396 |
if template == 'json': |
| 397 |
renderer = self.renderers.get('json', self.template_path) |
| 398 |
elif ':' in template: |
| 399 |
renderer_name, template = template.split(':', 1) |
| 400 |
renderer = self.renderers.get( |
| 401 |
renderer_name, |
| 402 |
self.template_path |
| 403 |
) |
| 404 |
if renderer is None: |
| 405 |
raise RuntimeError( |
| 406 |
'support for "%s" was not found; ' % renderer_name + |
| 407 |
'supported template engines are %s' % self.renderers.keys() |
| 408 |
) |
| 409 |
else: |
| 410 |
renderer = self.renderers.get( |
| 411 |
self.default_renderer, |
| 412 |
self.template_path |
| 413 |
) |
| 414 |
return renderer.render(template, namespace) |
| 415 |
|
| 416 |
def find_controller(self, state): |
| 417 |
''' |
| 418 |
The main request handler for Pecan applications. |
| 419 |
''' |
| 420 |
# get a sorted list of hooks, by priority (no controller hooks yet) |
| 421 |
req = state.request |
| 422 |
pecan_state = req.pecan |
| 423 |
|
| 424 |
# store the routing path for the current application to allow hooks to |
| 425 |
# modify it |
| 426 |
pecan_state['routing_path'] = path = req.path_info |
| 427 |
|
| 428 |
# handle "on_route" hooks |
| 429 |
self.handle_hooks(self.hooks, 'on_route', state) |
| 430 |
|
| 431 |
# lookup the controller, respecting content-type as requested |
| 432 |
# by the file extension on the URI |
| 433 |
pecan_state['extension'] = None |
| 434 |
|
| 435 |
# attempt to guess the content type based on the file extension |
| 436 |
if self.guess_content_type_from_ext \ |
| 437 |
and not pecan_state['content_type'] \ |
| 438 |
and '.' in path: |
| 439 |
_, extension = splitext(path.rstrip('/')) |
| 440 |
|
| 441 |
# preface with a letter to ensure compat for 2.5 |
| 442 |
potential_type = guess_type('x' + extension)[0] |
| 443 |
|
| 444 |
if extension and potential_type is not None: |
| 445 |
path = ''.join(path.rsplit(extension, 1)) |
| 446 |
pecan_state['extension'] = extension |
| 447 |
pecan_state['content_type'] = potential_type |
| 448 |
|
| 449 |
controller, remainder = self.route(req, self.root, path) |
| 450 |
cfg = _cfg(controller) |
| 451 |
|
| 452 |
if cfg.get('generic_handler'): |
| 453 |
raise exc.HTTPNotFound |
| 454 |
|
| 455 |
# handle generic controllers |
| 456 |
im_self = None |
| 457 |
if cfg.get('generic'): |
| 458 |
im_self = controller.__self__ |
| 459 |
handlers = cfg['generic_handlers'] |
| 460 |
controller = handlers.get(req.method, handlers['DEFAULT']) |
| 461 |
handle_security(controller, im_self) |
| 462 |
cfg = _cfg(controller) |
| 463 |
|
| 464 |
# add the controller to the state so that hooks can use it |
| 465 |
state.controller = controller |
| 466 |
|
| 467 |
# if unsure ask the controller for the default content type |
| 468 |
content_types = cfg.get('content_types', {}) |
| 469 |
if not pecan_state['content_type']: |
| 470 |
# attempt to find a best match based on accept headers (if they |
| 471 |
# exist) |
| 472 |
accept = getattr(req.accept, 'header_value', '*/*') or '*/*' |
| 473 |
if accept == '*/*' or ( |
| 474 |
accept.startswith('text/html,') and |
| 475 |
list(content_types.keys()) in self.SIMPLEST_CONTENT_TYPES): |
| 476 |
pecan_state['content_type'] = cfg.get( |
| 477 |
'content_type', |
| 478 |
'text/html' |
| 479 |
) |
| 480 |
else: |
| 481 |
best_default = None |
| 482 |
accept_header = acceptparse.create_accept_header(accept) |
| 483 |
offers = accept_header.acceptable_offers( |
| 484 |
list(content_types.keys()) |
| 485 |
) |
| 486 |
if offers: |
| 487 |
# If content type matches exactly use matched type |
| 488 |
best_default = offers[0][0] |
| 489 |
else: |
| 490 |
# If content type doesn't match exactly see if something |
| 491 |
# matches when not using parameters |
| 492 |
for k in content_types.keys(): |
| 493 |
if accept.startswith(k): |
| 494 |
best_default = k |
| 495 |
break |
| 496 |
|
| 497 |
if best_default is None: |
| 498 |
msg = "Controller '%s' defined does not support " + \ |
| 499 |
"content_type '%s'. Supported type(s): %s" |
| 500 |
logger.error( |
| 501 |
msg % ( |
| 502 |
controller.__name__, |
| 503 |
pecan_state['content_type'], |
| 504 |
content_types.keys() |
| 505 |
) |
| 506 |
) |
| 507 |
raise exc.HTTPNotAcceptable() |
| 508 |
|
| 509 |
pecan_state['content_type'] = best_default |
| 510 |
elif cfg.get('content_type') is not None and \ |
| 511 |
pecan_state['content_type'] not in content_types: |
| 512 |
|
| 513 |
msg = "Controller '%s' defined does not support content_type " + \ |
| 514 |
"'%s'. Supported type(s): %s" |
| 515 |
logger.error( |
| 516 |
msg % ( |
| 517 |
controller.__name__, |
| 518 |
pecan_state['content_type'], |
| 519 |
content_types.keys() |
| 520 |
) |
| 521 |
) |
| 522 |
raise exc.HTTPNotFound |
| 523 |
|
| 524 |
# fetch any parameters |
| 525 |
if req.method == 'GET': |
| 526 |
params = req.GET |
| 527 |
elif req.content_type in ('application/json', |
| 528 |
'application/javascript'): |
| 529 |
try: |
| 530 |
if not isinstance(req.json, dict): |
| 531 |
raise TypeError('%s is not a dict' % req.json) |
| 532 |
params = NestedMultiDict(req.GET, req.json) |
| 533 |
except (TypeError, ValueError): |
| 534 |
params = req.params |
| 535 |
else: |
| 536 |
params = req.params |
| 537 |
|
| 538 |
# fetch the arguments for the controller |
| 539 |
args, varargs, kwargs = self.get_args( |
| 540 |
state, |
| 541 |
params.mixed(), |
| 542 |
remainder, |
| 543 |
cfg['argspec'], |
| 544 |
im_self |
| 545 |
) |
| 546 |
state.arguments = Arguments(args, varargs, kwargs) |
| 547 |
|
| 548 |
# handle "before" hooks |
| 549 |
self.handle_hooks(self.determine_hooks(controller), 'before', state) |
| 550 |
|
| 551 |
return controller, args + varargs, kwargs |
| 552 |
|
| 553 |
def invoke_controller(self, controller, args, kwargs, state): |
| 554 |
''' |
| 555 |
The main request handler for Pecan applications. |
| 556 |
''' |
| 557 |
cfg = _cfg(controller) |
| 558 |
content_types = cfg.get('content_types', {}) |
| 559 |
req = state.request |
| 560 |
resp = state.response |
| 561 |
pecan_state = req.pecan |
| 562 |
|
| 563 |
# If a keyword is supplied via HTTP GET or POST arguments, but the |
| 564 |
# function signature does not allow it, just drop it (rather than |
| 565 |
# generating a TypeError). |
| 566 |
argspec = getargspec(controller) |
| 567 |
keys = kwargs.keys() |
| 568 |
for key in keys: |
| 569 |
if key not in argspec.args and not argspec.keywords: |
| 570 |
kwargs.pop(key) |
| 571 |
|
| 572 |
# get the result from the controller |
| 573 |
result = controller(*args, **kwargs) |
| 574 |
|
| 575 |
# a controller can return the response object which means they've taken |
| 576 |
# care of filling it out |
| 577 |
if result is response: |
| 578 |
return |
| 579 |
elif isinstance(result, WebObResponse): |
| 580 |
state.response = result |
| 581 |
return |
| 582 |
|
| 583 |
raw_namespace = result |
| 584 |
|
| 585 |
# pull the template out based upon content type and handle overrides |
| 586 |
template = content_types.get(pecan_state['content_type']) |
| 587 |
|
| 588 |
# check if for controller override of template |
| 589 |
template = pecan_state.get('override_template', template) |
| 590 |
if template is None and cfg['explicit_content_type'] is False: |
| 591 |
if self.default_renderer == 'json': |
| 592 |
template = 'json' |
| 593 |
|
| 594 |
pecan_state['content_type'] = pecan_state.get( |
| 595 |
'override_content_type', |
| 596 |
pecan_state['content_type'] |
| 597 |
) |
| 598 |
|
| 599 |
# if there is a template, render it |
| 600 |
if template: |
| 601 |
if template == 'json': |
| 602 |
pecan_state['content_type'] = 'application/json' |
| 603 |
result = self.render(template, result) |
| 604 |
|
| 605 |
# If we are in a test request put the namespace where it can be |
| 606 |
# accessed directly |
| 607 |
if req.environ.get('paste.testing'): |
| 608 |
testing_variables = req.environ['paste.testing_variables'] |
| 609 |
testing_variables['namespace'] = raw_namespace |
| 610 |
testing_variables['template_name'] = template |
| 611 |
testing_variables['controller_output'] = result |
| 612 |
|
| 613 |
# set the body content |
| 614 |
if result and isinstance(result, str): |
| 615 |
resp.text = result |
| 616 |
elif result: |
| 617 |
resp.body = result |
| 618 |
|
| 619 |
if pecan_state['content_type']: |
| 620 |
# set the content type |
| 621 |
resp.content_type = pecan_state['content_type'] |
| 622 |
|
| 623 |
def _handle_empty_response_body(self, state): |
| 624 |
# Enforce HTTP 204 for responses which contain no body |
| 625 |
if state.response.status_int == 200: |
| 626 |
# If the response is a generator... |
| 627 |
if isinstance(state.response.app_iter, types.GeneratorType): |
| 628 |
# Split the generator into two so we can peek at one of them |
| 629 |
# and determine if there is any response body content |
| 630 |
a, b = tee(state.response.app_iter) |
| 631 |
try: |
| 632 |
next(a) |
| 633 |
except StopIteration: |
| 634 |
# If we hit StopIteration, the body is empty |
| 635 |
state.response.status = 204 |
| 636 |
finally: |
| 637 |
state.response.app_iter = b |
| 638 |
else: |
| 639 |
text = None |
| 640 |
if state.response.charset: |
| 641 |
# `response.text` cannot be accessed without a valid |
| 642 |
# charset (because we don't know which encoding to use) |
| 643 |
try: |
| 644 |
text = state.response.text |
| 645 |
except UnicodeDecodeError: |
| 646 |
# If a valid charset is not specified, don't bother |
| 647 |
# trying to guess it (because there's obviously |
| 648 |
# content, so we know this shouldn't be a 204) |
| 649 |
pass |
| 650 |
if not any((state.response.body, text)): |
| 651 |
state.response.status = 204 |
| 652 |
|
| 653 |
if state.response.status_int in (204, 304): |
| 654 |
state.response.content_type = None |
| 655 |
|
| 656 |
def __call__(self, environ, start_response): |
| 657 |
''' |
| 658 |
Implements the WSGI specification for Pecan applications, utilizing |
| 659 |
``WebOb``. |
| 660 |
''' |
| 661 |
|
| 662 |
# create the request and response object |
| 663 |
req = self.request_cls(environ) |
| 664 |
resp = self.response_cls() |
| 665 |
state = RoutingState(req, resp, self) |
| 666 |
environ['pecan.locals'] = { |
| 667 |
'request': req, |
| 668 |
'response': resp |
| 669 |
} |
| 670 |
controller = None |
| 671 |
|
| 672 |
# track internal redirects |
| 673 |
internal_redirect = False |
| 674 |
|
| 675 |
# handle the request |
| 676 |
try: |
| 677 |
# add context and environment to the request |
| 678 |
req.context = environ.get('pecan.recursive.context', {}) |
| 679 |
req.pecan = dict(content_type=None) |
| 680 |
|
| 681 |
controller, args, kwargs = self.find_controller(state) |
| 682 |
self.invoke_controller(controller, args, kwargs, state) |
| 683 |
except Exception as e: |
| 684 |
# if this is an HTTP Exception, set it as the response |
| 685 |
if isinstance(e, exc.HTTPException): |
| 686 |
# if the client asked for JSON, do our best to provide it |
| 687 |
accept_header = acceptparse.create_accept_header( |
| 688 |
getattr(req.accept, 'header_value', '*/*') or '*/*') |
| 689 |
offers = accept_header.acceptable_offers( |
| 690 |
('text/plain', 'text/html', 'application/json')) |
| 691 |
best_match = offers[0][0] if offers else None |
| 692 |
state.response = e |
| 693 |
if best_match == 'application/json': |
| 694 |
json_body = dumps({ |
| 695 |
'code': e.status_int, |
| 696 |
'title': e.title, |
| 697 |
'description': e.detail |
| 698 |
}) |
| 699 |
if isinstance(json_body, str): |
| 700 |
e.text = json_body |
| 701 |
else: |
| 702 |
e.body = json_body |
| 703 |
state.response.content_type = best_match |
| 704 |
environ['pecan.original_exception'] = e |
| 705 |
|
| 706 |
# note if this is an internal redirect |
| 707 |
internal_redirect = isinstance(e, ForwardRequestException) |
| 708 |
|
| 709 |
# if this is not an internal redirect, run error hooks |
| 710 |
on_error_result = None |
| 711 |
if not internal_redirect: |
| 712 |
on_error_result = self.handle_hooks( |
| 713 |
self.determine_hooks(state.controller), |
| 714 |
'on_error', |
| 715 |
state, |
| 716 |
e |
| 717 |
) |
| 718 |
|
| 719 |
# if the on_error handler returned a Response, use it. |
| 720 |
if isinstance(on_error_result, WebObResponse): |
| 721 |
state.response = on_error_result |
| 722 |
else: |
| 723 |
if not isinstance(e, exc.HTTPException): |
| 724 |
raise |
| 725 |
|
| 726 |
# if this is an HTTP 405, attempt to specify an Allow header |
| 727 |
if isinstance(e, exc.HTTPMethodNotAllowed) and controller: |
| 728 |
allowed_methods = _cfg(controller).get('allowed_methods', []) |
| 729 |
if allowed_methods: |
| 730 |
state.response.allow = sorted(allowed_methods) |
| 731 |
finally: |
| 732 |
# if this is not an internal redirect, run "after" hooks |
| 733 |
if not internal_redirect: |
| 734 |
self.handle_hooks( |
| 735 |
self.determine_hooks(state.controller), |
| 736 |
'after', |
| 737 |
state |
| 738 |
) |
| 739 |
|
| 740 |
self._handle_empty_response_body(state) |
| 741 |
|
| 742 |
# get the response |
| 743 |
return state.response(environ, start_response) |
| 744 |
|
| 745 |
|
| 746 |
class ExplicitPecan(PecanBase): |
| 747 |
|
| 748 |
def get_args(self, state, all_params, remainder, argspec, im_self): |
| 749 |
# When comparing the argspec of the method to GET/POST params, |
| 750 |
# ignore the implicit (req, resp) at the beginning of the function |
| 751 |
# signature |
| 752 |
if hasattr(state.controller, '__self__'): |
| 753 |
_repr = '.'.join(( |
| 754 |
state.controller.__self__.__class__.__module__, |
| 755 |
state.controller.__self__.__class__.__name__, |
| 756 |
state.controller.__name__ |
| 757 |
)) |
| 758 |
else: |
| 759 |
_repr = '.'.join(( |
| 760 |
state.controller.__module__, |
| 761 |
state.controller.__name__ |
| 762 |
)) |
| 763 |
|
| 764 |
signature_error = TypeError( |
| 765 |
'When `use_context_locals` is `False`, pecan passes an explicit ' |
| 766 |
'reference to the request and response as the first two arguments ' |
| 767 |
'to the controller.\nChange the `%s` signature to accept exactly ' |
| 768 |
'2 initial arguments (req, resp)' % _repr |
| 769 |
) |
| 770 |
try: |
| 771 |
positional = argspec.args[:] |
| 772 |
positional.pop(1) # req |
| 773 |
positional.pop(1) # resp |
| 774 |
argspec = argspec._replace(args=positional) |
| 775 |
except IndexError: |
| 776 |
raise signature_error |
| 777 |
|
| 778 |
args, varargs, kwargs = super(ExplicitPecan, self).get_args( |
| 779 |
state, all_params, remainder, argspec, im_self |
| 780 |
) |
| 781 |
|
| 782 |
if ismethod(state.controller): |
| 783 |
args = [state.request, state.response] + args |
| 784 |
else: |
| 785 |
# generic controllers have an explicit self *first* |
| 786 |
# (because they're decorated functions, not instance methods) |
| 787 |
args[1:1] = [state.request, state.response] |
| 788 |
return args, varargs, kwargs |
| 789 |
|
| 790 |
|
| 791 |
class Pecan(PecanBase): |
| 792 |
''' |
| 793 |
Pecan application object. Generally created using ``pecan.make_app``, |
| 794 |
rather than being created manually. |
| 795 |
|
| 796 |
Creates a Pecan application instance, which is a WSGI application. |
| 797 |
|
| 798 |
:param root: A string representing a root controller object (e.g., |
| 799 |
"myapp.controller.root.RootController") |
| 800 |
:param default_renderer: The default template rendering engine to use. |
| 801 |
Defaults to mako. |
| 802 |
:param template_path: A relative file system path (from the project root) |
| 803 |
where template files live. Defaults to 'templates'. |
| 804 |
:param hooks: A callable which returns a list of |
| 805 |
:class:`pecan.hooks.PecanHook` |
| 806 |
:param custom_renderers: Custom renderer objects, as a dictionary keyed |
| 807 |
by engine name. |
| 808 |
:param extra_template_vars: Any variables to inject into the template |
| 809 |
namespace automatically. |
| 810 |
:param force_canonical: A boolean indicating if this project should |
| 811 |
require canonical URLs. |
| 812 |
:param guess_content_type_from_ext: A boolean indicating if this project |
| 813 |
should use the extension in the URL for guessing |
| 814 |
the content type to return. |
| 815 |
:param use_context_locals: When `True`, `pecan.request` and |
| 816 |
`pecan.response` will be available as |
| 817 |
thread-local references. |
| 818 |
:param request_cls: Can be used to specify a custom `pecan.request` object. |
| 819 |
Defaults to `pecan.Request`. |
| 820 |
:param response_cls: Can be used to specify a custom `pecan.response` |
| 821 |
object. Defaults to `pecan.Response`. |
| 822 |
''' |
| 823 |
|
| 824 |
def __new__(cls, *args, **kw): |
| 825 |
if kw.get('use_context_locals') is False: |
| 826 |
self = super(Pecan, cls).__new__(ExplicitPecan, *args, **kw) |
| 827 |
self.__init__(*args, **kw) |
| 828 |
return self |
| 829 |
return super(Pecan, cls).__new__(cls) |
| 830 |
|
| 831 |
def __init__(self, *args, **kw): |
| 832 |
self.init_context_local(kw.get('context_local_factory')) |
| 833 |
super(Pecan, self).__init__(*args, **kw) |
| 834 |
|
| 835 |
def __call__(self, environ, start_response): |
| 836 |
try: |
| 837 |
state.hooks = [] |
| 838 |
state.app = self |
| 839 |
state.controller = None |
| 840 |
state.arguments = None |
| 841 |
return super(Pecan, self).__call__(environ, start_response) |
| 842 |
finally: |
| 843 |
del state.hooks |
| 844 |
del state.request |
| 845 |
del state.response |
| 846 |
del state.controller |
| 847 |
del state.arguments |
| 848 |
del state.app |
| 849 |
|
| 850 |
def init_context_local(self, local_factory): |
| 851 |
global state |
| 852 |
if local_factory is None: |
| 853 |
from threading import local as local_factory |
| 854 |
state = local_factory() |
| 855 |
|
| 856 |
def find_controller(self, _state): |
| 857 |
state.request = _state.request |
| 858 |
state.response = _state.response |
| 859 |
controller, args, kw = super(Pecan, self).find_controller(_state) |
| 860 |
state.controller = controller |
| 861 |
state.arguments = _state.arguments |
| 862 |
return controller, args, kw |
| 863 |
|
| 864 |
def handle_hooks(self, hooks, *args, **kw): |
| 865 |
state.hooks = hooks |
| 866 |
return super(Pecan, self).handle_hooks(hooks, *args, **kw) |