| 1 |
import builtins |
| 2 |
import types |
| 3 |
import sys |
| 4 |
from inspect import getmembers |
| 5 |
|
| 6 |
from webob.exc import HTTPFound |
| 7 |
|
| 8 |
from .util import iscontroller, _cfg |
| 9 |
|
| 10 |
__all__ = [ |
| 11 |
'PecanHook', 'TransactionHook', 'HookController', |
| 12 |
'RequestViewerHook' |
| 13 |
] |
| 14 |
|
| 15 |
|
| 16 |
def walk_controller(root_class, controller, hooks, seen=None): |
| 17 |
seen = seen or set() |
| 18 |
if type(controller) not in vars(builtins).values(): |
| 19 |
# Avoid recursion loops |
| 20 |
try: |
| 21 |
if controller in seen: |
| 22 |
return |
| 23 |
seen.add(controller) |
| 24 |
except TypeError: |
| 25 |
# If we discover an unhashable item (like a list), it's not |
| 26 |
# something that we want to traverse because it's not the sort of |
| 27 |
# thing we would add a hook to |
| 28 |
return |
| 29 |
|
| 30 |
for hook in getattr(controller, '__hooks__', []): |
| 31 |
# Append hooks from controller class definition |
| 32 |
hooks.add(hook) |
| 33 |
|
| 34 |
for name, value in getmembers(controller): |
| 35 |
if name == 'controller': |
| 36 |
continue |
| 37 |
if name.startswith('__') and name.endswith('__'): |
| 38 |
continue |
| 39 |
|
| 40 |
if iscontroller(value): |
| 41 |
for hook in hooks: |
| 42 |
value._pecan.setdefault('hooks', set()).add(hook) |
| 43 |
elif hasattr(value, '__class__'): |
| 44 |
# Skip non-exposed methods that are defined in parent classes; |
| 45 |
# they're internal implementation details of that class, and |
| 46 |
# not actual routable controllers, so we shouldn't bother |
| 47 |
# assigning hooks to them. |
| 48 |
if ( |
| 49 |
isinstance(value, types.MethodType) and |
| 50 |
any(filter(lambda c: value.__func__ in c.__dict__.values(), |
| 51 |
value.__self__.__class__.mro()[1:])) |
| 52 |
): |
| 53 |
continue |
| 54 |
walk_controller(root_class, value, hooks, seen) |
| 55 |
|
| 56 |
|
| 57 |
class HookControllerMeta(type): |
| 58 |
''' |
| 59 |
A base class for controllers that would like to specify hooks on |
| 60 |
their controller methods. Simply create a list of hook objects |
| 61 |
called ``__hooks__`` as a member of the controller's namespace. |
| 62 |
''' |
| 63 |
|
| 64 |
def __init__(cls, name, bases, dict_): |
| 65 |
hooks = set(dict_.get('__hooks__', [])) |
| 66 |
for base in bases: |
| 67 |
# Add hooks from parent class and mixins |
| 68 |
for hook in getattr(base, '__hooks__', []): |
| 69 |
hooks.add(hook) |
| 70 |
walk_controller(cls, cls, hooks) |
| 71 |
|
| 72 |
|
| 73 |
HookController = HookControllerMeta( |
| 74 |
'HookController', |
| 75 |
(object,), |
| 76 |
{'__doc__': ("A base class for controllers that would like to specify " |
| 77 |
"hooks on their controller methods. Simply create a list " |
| 78 |
"of hook objects called ``__hooks__`` as a class attribute " |
| 79 |
"of your controller.")} |
| 80 |
) |
| 81 |
|
| 82 |
|
| 83 |
class PecanHook(object): |
| 84 |
''' |
| 85 |
A base class for Pecan hooks. Inherit from this class to create your |
| 86 |
own hooks. Set a priority on a hook by setting the ``priority`` |
| 87 |
attribute for the hook, which defaults to 100. |
| 88 |
''' |
| 89 |
|
| 90 |
priority = 100 |
| 91 |
|
| 92 |
def on_route(self, state): |
| 93 |
''' |
| 94 |
Override this method to create a hook that gets called upon |
| 95 |
the start of routing. |
| 96 |
|
| 97 |
:param state: The Pecan ``state`` object for the current request. |
| 98 |
''' |
| 99 |
return |
| 100 |
|
| 101 |
def before(self, state): |
| 102 |
''' |
| 103 |
Override this method to create a hook that gets called after |
| 104 |
routing, but before the request gets passed to your controller. |
| 105 |
|
| 106 |
:param state: The Pecan ``state`` object for the current request. |
| 107 |
''' |
| 108 |
return |
| 109 |
|
| 110 |
def after(self, state): |
| 111 |
''' |
| 112 |
Override this method to create a hook that gets called after |
| 113 |
the request has been handled by the controller. |
| 114 |
|
| 115 |
:param state: The Pecan ``state`` object for the current request. |
| 116 |
''' |
| 117 |
return |
| 118 |
|
| 119 |
def on_error(self, state, e): |
| 120 |
''' |
| 121 |
Override this method to create a hook that gets called upon |
| 122 |
an exception being raised in your controller. |
| 123 |
|
| 124 |
:param state: The Pecan ``state`` object for the current request. |
| 125 |
:param e: The ``Exception`` object that was raised. |
| 126 |
''' |
| 127 |
return |
| 128 |
|
| 129 |
|
| 130 |
class TransactionHook(PecanHook): |
| 131 |
''' |
| 132 |
:param start: A callable that will bind to a writable database and |
| 133 |
start a transaction. |
| 134 |
:param start_ro: A callable that will bind to a readable database. |
| 135 |
:param commit: A callable that will commit the active transaction. |
| 136 |
:param rollback: A callable that will roll back the active |
| 137 |
transaction. |
| 138 |
:param clear: A callable that will clear your current context. |
| 139 |
|
| 140 |
A basic framework hook for supporting wrapping requests in |
| 141 |
transactions. By default, it will wrap all but ``GET`` and ``HEAD`` |
| 142 |
requests in a transaction. Override the ``is_transactional`` method |
| 143 |
to define your own rules for what requests should be transactional. |
| 144 |
''' |
| 145 |
|
| 146 |
def __init__(self, start, start_ro, commit, rollback, clear): |
| 147 |
|
| 148 |
self.start = start |
| 149 |
self.start_ro = start_ro |
| 150 |
self.commit = commit |
| 151 |
self.rollback = rollback |
| 152 |
self.clear = clear |
| 153 |
|
| 154 |
def is_transactional(self, state): |
| 155 |
''' |
| 156 |
Decide if a request should be wrapped in a transaction, based |
| 157 |
upon the state of the request. By default, wraps all but ``GET`` |
| 158 |
and ``HEAD`` requests in a transaction, along with respecting |
| 159 |
the ``transactional`` decorator from :mod:pecan.decorators. |
| 160 |
|
| 161 |
:param state: The Pecan state object for the current request. |
| 162 |
''' |
| 163 |
|
| 164 |
controller = getattr(state, 'controller', None) |
| 165 |
if controller: |
| 166 |
force_transactional = _cfg(controller).get('transactional', False) |
| 167 |
else: |
| 168 |
force_transactional = False |
| 169 |
|
| 170 |
if state.request.method not in ('GET', 'HEAD') or force_transactional: |
| 171 |
return True |
| 172 |
return False |
| 173 |
|
| 174 |
def on_route(self, state): |
| 175 |
state.request.error = False |
| 176 |
if self.is_transactional(state): |
| 177 |
state.request.transactional = True |
| 178 |
self.start() |
| 179 |
else: |
| 180 |
state.request.transactional = False |
| 181 |
self.start_ro() |
| 182 |
|
| 183 |
def before(self, state): |
| 184 |
if self.is_transactional(state) \ |
| 185 |
and not getattr(state.request, 'transactional', False): |
| 186 |
self.clear() |
| 187 |
state.request.transactional = True |
| 188 |
self.start() |
| 189 |
|
| 190 |
def on_error(self, state, e): |
| 191 |
# |
| 192 |
# If we should ignore redirects, |
| 193 |
# (e.g., shouldn't consider them rollback-worthy) |
| 194 |
# don't set `state.request.error = True`. |
| 195 |
# |
| 196 |
trans_ignore_redirects = ( |
| 197 |
state.request.method not in ('GET', 'HEAD') |
| 198 |
) |
| 199 |
if state.controller is not None: |
| 200 |
trans_ignore_redirects = ( |
| 201 |
_cfg(state.controller).get( |
| 202 |
'transactional_ignore_redirects', |
| 203 |
trans_ignore_redirects |
| 204 |
) |
| 205 |
) |
| 206 |
if type(e) is HTTPFound and trans_ignore_redirects is True: |
| 207 |
return |
| 208 |
state.request.error = True |
| 209 |
|
| 210 |
def after(self, state): |
| 211 |
if getattr(state.request, 'transactional', False): |
| 212 |
action_name = None |
| 213 |
if state.request.error: |
| 214 |
action_name = 'after_rollback' |
| 215 |
self.rollback() |
| 216 |
else: |
| 217 |
action_name = 'after_commit' |
| 218 |
self.commit() |
| 219 |
|
| 220 |
# |
| 221 |
# If a controller was routed to, find any |
| 222 |
# after_* actions it may have registered, and perform |
| 223 |
# them. |
| 224 |
# |
| 225 |
if action_name: |
| 226 |
controller = getattr(state, 'controller', None) |
| 227 |
if controller is not None: |
| 228 |
actions = _cfg(controller).get(action_name, []) |
| 229 |
for action in actions: |
| 230 |
action() |
| 231 |
|
| 232 |
self.clear() |
| 233 |
|
| 234 |
|
| 235 |
class RequestViewerHook(PecanHook): |
| 236 |
''' |
| 237 |
:param config: A (optional) dictionary that can hold ``items`` and/or |
| 238 |
``blacklist`` keys. |
| 239 |
:param writer: The stream writer to use. Can redirect output to other |
| 240 |
streams as long as the passed in stream has a |
| 241 |
``write`` callable method. |
| 242 |
:param terminal: Outputs to the chosen stream writer (usually |
| 243 |
the terminal) |
| 244 |
:param headers: Sets values to the X-HTTP headers |
| 245 |
|
| 246 |
Returns some information about what is going on in a single request. It |
| 247 |
accepts specific items to report on but uses a default list of items when |
| 248 |
none are passed in. Based on the requested ``url``, items can also be |
| 249 |
blacklisted. |
| 250 |
Configuration is flexible, can be passed in (or not) and can contain |
| 251 |
some or all the keys supported. |
| 252 |
|
| 253 |
**items** |
| 254 |
|
| 255 |
This key holds the items that this hook will display. When this key is |
| 256 |
passed only the items in the list will be used. Valid items are *any* |
| 257 |
item that the ``request`` object holds, by default it uses the |
| 258 |
following: |
| 259 |
|
| 260 |
* path |
| 261 |
* status |
| 262 |
* method |
| 263 |
* controller |
| 264 |
* params |
| 265 |
* hooks |
| 266 |
|
| 267 |
.. note:: |
| 268 |
This key should always use a ``list`` of items to use. |
| 269 |
|
| 270 |
**blacklist** |
| 271 |
|
| 272 |
This key holds items that will be blacklisted based on ``url``. If |
| 273 |
there is a need to omit urls that start with `/javascript`, then this |
| 274 |
key would look like:: |
| 275 |
|
| 276 |
'blacklist': ['/javascript'] |
| 277 |
|
| 278 |
As many blacklisting items as needed can be contained in the list. The hook |
| 279 |
will verify that the url is not starting with items in this list to display |
| 280 |
results, otherwise it will get omitted. |
| 281 |
|
| 282 |
.. note:: |
| 283 |
This key should always use a ``list`` of items to use. |
| 284 |
|
| 285 |
For more detailed documentation about this hook, please see |
| 286 |
:ref:`requestviewerhook` |
| 287 |
''' |
| 288 |
|
| 289 |
available = ['path', 'status', 'method', 'controller', 'params', 'hooks'] |
| 290 |
|
| 291 |
def __init__(self, config=None, writer=sys.stdout, terminal=True, |
| 292 |
headers=True): |
| 293 |
|
| 294 |
if not config: |
| 295 |
self.config = {'items': self.available} |
| 296 |
else: |
| 297 |
if config.__class__.__name__ == 'Config': |
| 298 |
self.config = config.to_dict() |
| 299 |
else: |
| 300 |
self.config = config |
| 301 |
self.writer = writer |
| 302 |
self.items = self.config.get('items', self.available) |
| 303 |
self.blacklist = self.config.get('blacklist', []) |
| 304 |
self.terminal = terminal |
| 305 |
self.headers = headers |
| 306 |
|
| 307 |
def after(self, state): |
| 308 |
|
| 309 |
# Default and/or custom response information |
| 310 |
responses = { |
| 311 |
'controller': lambda self, state: self.get_controller(state), |
| 312 |
'method': lambda self, state: state.request.method, |
| 313 |
'path': lambda self, state: state.request.path, |
| 314 |
'params': lambda self, state: [ |
| 315 |
(p[0].encode('utf-8'), p[1].encode('utf-8')) |
| 316 |
for p in state.request.params.items() |
| 317 |
], |
| 318 |
'status': lambda self, state: state.response.status, |
| 319 |
'hooks': lambda self, state: self.format_hooks(state.app.hooks), |
| 320 |
} |
| 321 |
|
| 322 |
is_available = [ |
| 323 |
i for i in self.items |
| 324 |
if i in self.available or hasattr(state.request, i) |
| 325 |
] |
| 326 |
|
| 327 |
terminal = [] |
| 328 |
headers = [] |
| 329 |
will_skip = [ |
| 330 |
i for i in self.blacklist |
| 331 |
if state.request.path.startswith(i) |
| 332 |
] |
| 333 |
|
| 334 |
if will_skip: |
| 335 |
return |
| 336 |
|
| 337 |
for request_info in is_available: |
| 338 |
try: |
| 339 |
value = responses.get(request_info) |
| 340 |
if not value: |
| 341 |
value = getattr(state.request, request_info) |
| 342 |
else: |
| 343 |
value = value(self, state) |
| 344 |
except Exception as e: |
| 345 |
value = e |
| 346 |
|
| 347 |
terminal.append('%-12s - %s\n' % (request_info, value)) |
| 348 |
headers.append((request_info, value)) |
| 349 |
|
| 350 |
if self.terminal: |
| 351 |
self.writer.write(''.join(terminal)) |
| 352 |
self.writer.write('\n\n') |
| 353 |
|
| 354 |
if self.headers: |
| 355 |
for h in headers: |
| 356 |
key = str(h[0]) |
| 357 |
value = str(h[1]) |
| 358 |
name = 'X-Pecan-%s' % key |
| 359 |
state.response.headers[name] = value |
| 360 |
|
| 361 |
def get_controller(self, state): |
| 362 |
''' |
| 363 |
Retrieves the actual controller name from the application |
| 364 |
Specific to Pecan (not available in the request object) |
| 365 |
''' |
| 366 |
path = state.request.pecan['routing_path'].split('/')[1:] |
| 367 |
return state.controller.__str__().split()[2] |
| 368 |
|
| 369 |
def format_hooks(self, hooks): |
| 370 |
''' |
| 371 |
Tries to format the hook objects to be more readable |
| 372 |
Specific to Pecan (not available in the request object) |
| 373 |
''' |
| 374 |
str_hooks = [str(i).split()[0].strip('<') for i in hooks] |
| 375 |
return [i.split('.')[-1] for i in str_hooks if '.' in i] |