| 1 |
.. _hooks: |
| 2 |
|
| 3 |
Pecan Hooks |
| 4 |
=========== |
| 5 |
|
| 6 |
Although it is easy to use WSGI middleware with Pecan, it can be hard |
| 7 |
(sometimes impossible) to have access to Pecan's internals from within |
| 8 |
middleware. Pecan Hooks are a way to interact with the framework, |
| 9 |
without having to write separate middleware. |
| 10 |
|
| 11 |
Hooks allow you to execute code at key points throughout the life cycle of your request: |
| 12 |
|
| 13 |
* :func:`~pecan.hooks.PecanHook.on_route`: called before Pecan attempts to |
| 14 |
route a request to a controller |
| 15 |
|
| 16 |
* :func:`~pecan.hooks.PecanHook.before`: called after routing, but before |
| 17 |
controller code is run |
| 18 |
|
| 19 |
* :func:`~pecan.hooks.PecanHook.after`: called after controller code has been |
| 20 |
run |
| 21 |
|
| 22 |
* :func:`~pecan.hooks.PecanHook.on_error`: called when a request generates an |
| 23 |
exception |
| 24 |
|
| 25 |
Implementating a Pecan Hook |
| 26 |
--------------------------- |
| 27 |
|
| 28 |
In the below example, a simple hook will gather some information about |
| 29 |
the request and print it to ``stdout``. |
| 30 |
|
| 31 |
Your hook implementation needs to import :class:`~pecan.hooks.PecanHook` so it |
| 32 |
can be used as a base class. From there, you'll want to override the |
| 33 |
:func:`~pecan.hooks.PecanHook.on_route`, :func:`~pecan.hooks.PecanHook.before`, |
| 34 |
:func:`~pecan.hooks.PecanHook.after`, or |
| 35 |
:func:`~pecan.hooks.PecanHook.on_error` methods to |
| 36 |
define behavior. |
| 37 |
|
| 38 |
:: |
| 39 |
|
| 40 |
from pecan.hooks import PecanHook |
| 41 |
|
| 42 |
class SimpleHook(PecanHook): |
| 43 |
|
| 44 |
def before(self, state): |
| 45 |
print "\nabout to enter the controller..." |
| 46 |
|
| 47 |
def after(self, state): |
| 48 |
print "\nmethod: \t %s" % state.request.method |
| 49 |
print "\nresponse: \t %s" % state.response.status |
| 50 |
|
| 51 |
:func:`~pecan.hooks.PecanHook.on_route`, :func:`~pecan.hooks.PecanHook.before`, |
| 52 |
and :func:`~pecan.hooks.PecanHook.after` are each passed a shared |
| 53 |
state object which includes useful information, such as the request and |
| 54 |
response objects, and which controller was selected by Pecan's routing:: |
| 55 |
|
| 56 |
class SimpleHook(PecanHook): |
| 57 |
|
| 58 |
def on_route(self, state): |
| 59 |
print "\nabout to map the URL to a Python method (controller)..." |
| 60 |
assert state.controller is None # Routing hasn't occurred yet |
| 61 |
assert isinstance(state.request, webob.Request) |
| 62 |
assert isinstance(state.response, webob.Response) |
| 63 |
assert isinstance(state.hooks, list) # A list of hooks to apply |
| 64 |
|
| 65 |
def before(self, state): |
| 66 |
print "\nabout to enter the controller..." |
| 67 |
if state.request.path == '/': |
| 68 |
# |
| 69 |
# `state.controller` is a reference to the actual |
| 70 |
# `@pecan.expose()`-ed controller that will be routed to |
| 71 |
# and used to generate the response body |
| 72 |
# |
| 73 |
assert state.controller.__func__ is RootController.index.__func__ |
| 74 |
assert isinstance(state.arguments, inspect.Arguments) |
| 75 |
print state.arguments.args |
| 76 |
print state.arguments.varargs |
| 77 |
print state.arguments.keywords |
| 78 |
assert isinstance(state.request, webob.Request) |
| 79 |
assert isinstance(state.response, webob.Response) |
| 80 |
assert isinstance(state.hooks, list) |
| 81 |
|
| 82 |
|
| 83 |
:func:`~pecan.hooks.PecanHook.on_error` is passed a shared state object **and** |
| 84 |
the original exception. If an :func:`~pecan.hooks.PecanHook.on_error` handler |
| 85 |
returns a Response object, this response will be returned to the end user and |
| 86 |
no furthur :func:`~pecan.hooks.PecanHook.on_error` hooks will be executed:: |
| 87 |
|
| 88 |
class CustomErrorHook(PecanHook): |
| 89 |
|
| 90 |
def on_error(self, state, exc): |
| 91 |
if isinstance(exc, SomeExceptionType): |
| 92 |
return webob.Response('Custom Error!', status=500) |
| 93 |
|
| 94 |
.. _attaching_hooks: |
| 95 |
|
| 96 |
Attaching Hooks |
| 97 |
--------------- |
| 98 |
|
| 99 |
Hooks can be attached in a project-wide manner by specifying a list of hooks |
| 100 |
in your project's configuration file. |
| 101 |
|
| 102 |
:: |
| 103 |
|
| 104 |
app = { |
| 105 |
'root' : '...' |
| 106 |
# ... |
| 107 |
'hooks': lambda: [SimpleHook()] |
| 108 |
} |
| 109 |
|
| 110 |
Hooks can also be applied selectively to controllers and their sub-controllers |
| 111 |
using the :attr:`__hooks__` attribute on one or more controllers and |
| 112 |
subclassing :class:`~pecan.hooks.HookController`. |
| 113 |
|
| 114 |
:: |
| 115 |
|
| 116 |
from pecan import expose |
| 117 |
from pecan.hooks import HookController |
| 118 |
from my_hooks import SimpleHook |
| 119 |
|
| 120 |
class SimpleController(HookController): |
| 121 |
|
| 122 |
__hooks__ = [SimpleHook()] |
| 123 |
|
| 124 |
@expose('json') |
| 125 |
def index(self): |
| 126 |
print "DO SOMETHING!" |
| 127 |
return dict() |
| 128 |
|
| 129 |
Now that :class:`SimpleHook` is included, let's see what happens |
| 130 |
when we run the app and browse the application from our web browser. |
| 131 |
|
| 132 |
:: |
| 133 |
|
| 134 |
pecan serve config.py |
| 135 |
serving on 0.0.0.0:8080 view at http://127.0.0.1:8080 |
| 136 |
|
| 137 |
about to enter the controller... |
| 138 |
DO SOMETHING! |
| 139 |
method: GET |
| 140 |
response: 200 OK |
| 141 |
|
| 142 |
Hooks can be inherited from parent class or mixins. Just make sure to |
| 143 |
subclass from :class:`~pecan.hooks.HookController`. |
| 144 |
|
| 145 |
:: |
| 146 |
|
| 147 |
from pecan import expose |
| 148 |
from pecan.hooks import PecanHook, HookController |
| 149 |
|
| 150 |
class ParentHook(PecanHook): |
| 151 |
|
| 152 |
priority = 1 |
| 153 |
|
| 154 |
def before(self, state): |
| 155 |
print "\nabout to enter the parent controller..." |
| 156 |
|
| 157 |
class CommonHook(PecanHook): |
| 158 |
|
| 159 |
priority = 2 |
| 160 |
|
| 161 |
def before(self, state): |
| 162 |
print "\njust a common hook..." |
| 163 |
|
| 164 |
class SubHook(PecanHook): |
| 165 |
|
| 166 |
def before(self, state): |
| 167 |
print "\nabout to enter the subcontroller..." |
| 168 |
|
| 169 |
class SubMixin(object): |
| 170 |
__hooks__ = [SubHook()] |
| 171 |
|
| 172 |
# We'll use the same instance for both controllers, |
| 173 |
# to avoid double calls |
| 174 |
common = CommonHook() |
| 175 |
|
| 176 |
class SubController(HookController, SubMixin): |
| 177 |
|
| 178 |
__hooks__ = [common] |
| 179 |
|
| 180 |
@expose('json') |
| 181 |
def index(self): |
| 182 |
print "\nI AM THE SUB!" |
| 183 |
return dict() |
| 184 |
|
| 185 |
class RootController(HookController): |
| 186 |
|
| 187 |
__hooks__ = [common, ParentHook()] |
| 188 |
|
| 189 |
@expose('json') |
| 190 |
def index(self): |
| 191 |
print "\nI AM THE ROOT!" |
| 192 |
return dict() |
| 193 |
|
| 194 |
sub = SubController() |
| 195 |
|
| 196 |
Let's see what happens when we run the app. |
| 197 |
First loading the root controller: |
| 198 |
|
| 199 |
:: |
| 200 |
|
| 201 |
pecan serve config.py |
| 202 |
serving on 0.0.0.0:8080 view at http://127.0.0.1:8080 |
| 203 |
|
| 204 |
GET / HTTP/1.1" 200 |
| 205 |
|
| 206 |
about to enter the parent controller... |
| 207 |
|
| 208 |
just a common hook |
| 209 |
|
| 210 |
I AM THE ROOT! |
| 211 |
|
| 212 |
Then loading the sub controller: |
| 213 |
|
| 214 |
:: |
| 215 |
|
| 216 |
pecan serve config.py |
| 217 |
serving on 0.0.0.0:8080 view at http://127.0.0.1:8080 |
| 218 |
|
| 219 |
GET /sub HTTP/1.1" 200 |
| 220 |
|
| 221 |
about to enter the parent controller... |
| 222 |
|
| 223 |
just a common hook |
| 224 |
|
| 225 |
about to enter the subcontroller... |
| 226 |
|
| 227 |
I AM THE SUB! |
| 228 |
|
| 229 |
.. note:: |
| 230 |
|
| 231 |
Make sure to set proper priority values for nested hooks in order |
| 232 |
to get them executed in the desired order. |
| 233 |
|
| 234 |
.. warning:: |
| 235 |
|
| 236 |
Two hooks of the same type will be added/executed twice, if passed as |
| 237 |
different instances to a parent and a child controller. |
| 238 |
If passed as one instance variable - will be invoked once for both controllers. |
| 239 |
|
| 240 |
Hooks That Come with Pecan |
| 241 |
-------------------------- |
| 242 |
|
| 243 |
Pecan includes some hooks in its core. This section will describe |
| 244 |
their different uses, how to configure them, and examples of common |
| 245 |
scenarios. |
| 246 |
|
| 247 |
.. _requestviewerhook: |
| 248 |
|
| 249 |
RequestViewerHook |
| 250 |
''''''''''''''''' |
| 251 |
|
| 252 |
This hook is useful for debugging purposes. It has access to every |
| 253 |
attribute the ``response`` object has plus a few others that are specific to |
| 254 |
the framework. |
| 255 |
|
| 256 |
There are two main ways that this hook can provide information about a request: |
| 257 |
|
| 258 |
#. Terminal or logging output (via an file-like stream like ``stdout``) |
| 259 |
#. Custom header keys in the actual response. |
| 260 |
|
| 261 |
By default, both outputs are enabled. |
| 262 |
|
| 263 |
.. seealso:: |
| 264 |
|
| 265 |
* :ref:`pecan_hooks` |
| 266 |
|
| 267 |
Configuring RequestViewerHook |
| 268 |
............................. |
| 269 |
|
| 270 |
There are a few ways to get this hook properly configured and running. However, |
| 271 |
it is useful to know that no actual configuration is needed to have it up and |
| 272 |
running. |
| 273 |
|
| 274 |
By default it will output information about these items: |
| 275 |
|
| 276 |
* path : Displays the url that was used to generate this response |
| 277 |
* status : The response from the server (e.g. '200 OK') |
| 278 |
* method : The method for the request (e.g. 'GET', 'POST', 'PUT or 'DELETE') |
| 279 |
* controller : The actual controller method in Pecan responsible for the response |
| 280 |
* params : A list of tuples for the params passed in at request time |
| 281 |
* hooks : Any hooks that are used in the app will be listed here. |
| 282 |
|
| 283 |
The default configuration will show those values in the terminal via |
| 284 |
``stdout`` and it will also add them to the response headers (in the |
| 285 |
form of ``X-Pecan-item_name``). |
| 286 |
|
| 287 |
This is how the terminal output might look for a `/favicon.ico` request:: |
| 288 |
|
| 289 |
path - /favicon.ico |
| 290 |
status - 404 Not Found |
| 291 |
method - GET |
| 292 |
controller - The resource could not be found. |
| 293 |
params - [] |
| 294 |
hooks - ['RequestViewerHook'] |
| 295 |
|
| 296 |
In the above case, the file was not found, and the information was printed to |
| 297 |
`stdout`. Additionally, the following headers would be present in the HTTP |
| 298 |
response:: |
| 299 |
|
| 300 |
X-Pecan-path /favicon.ico |
| 301 |
X-Pecan-status 404 Not Found |
| 302 |
X-Pecan-method GET |
| 303 |
X-Pecan-controller The resource could not be found. |
| 304 |
X-Pecan-params [] |
| 305 |
X-Pecan-hooks ['RequestViewerHook'] |
| 306 |
|
| 307 |
The configuration dictionary is flexible (none of the keys are required) and |
| 308 |
can hold two keys: ``items`` and ``blacklist``. |
| 309 |
|
| 310 |
This is how the hook would look if configured directly (shortened for brevity):: |
| 311 |
|
| 312 |
... |
| 313 |
'hooks': lambda: [ |
| 314 |
RequestViewerHook({'items':['path']}) |
| 315 |
] |
| 316 |
|
| 317 |
Modifying Output Format |
| 318 |
....................... |
| 319 |
|
| 320 |
The ``items`` list specify the information that the hook will return. |
| 321 |
Sometimes you will need a specific piece of information or a certain |
| 322 |
bunch of them according to the development need so the defaults will |
| 323 |
need to be changed and a list of items specified. |
| 324 |
|
| 325 |
.. note:: |
| 326 |
|
| 327 |
When specifying a list of items, this list overrides completely the |
| 328 |
defaults, so if a single item is listed, only that item will be returned by |
| 329 |
the hook. |
| 330 |
|
| 331 |
The hook has access to every single attribute the request object has |
| 332 |
and not only to the default ones that are displayed, so you can fine tune the |
| 333 |
information displayed. |
| 334 |
|
| 335 |
These is a list containing all the possible attributes the hook has access to |
| 336 |
(directly from `webob`): |
| 337 |
|
| 338 |
====================== ========================== |
| 339 |
====================== ========================== |
| 340 |
accept make_tempfile |
| 341 |
accept_charset max_forwards |
| 342 |
accept_encoding method |
| 343 |
accept_language params |
| 344 |
application_url path |
| 345 |
as_string path_info |
| 346 |
authorization path_info_peek |
| 347 |
blank path_info_pop |
| 348 |
body path_qs |
| 349 |
body_file path_url |
| 350 |
body_file_raw postvars |
| 351 |
body_file_seekable pragma |
| 352 |
cache_control query_string |
| 353 |
call_application queryvars |
| 354 |
charset range |
| 355 |
content_length referer |
| 356 |
content_type referrer |
| 357 |
cookies relative_url |
| 358 |
copy remote_addr |
| 359 |
copy_body remote_user |
| 360 |
copy_get remove_conditional_headers |
| 361 |
date request_body_tempfile_limit |
| 362 |
decode_param_names scheme |
| 363 |
environ script_name |
| 364 |
from_file server_name |
| 365 |
from_string server_port |
| 366 |
get_response str_GET |
| 367 |
headers str_POST |
| 368 |
host str_cookies |
| 369 |
host_url str_params |
| 370 |
http_version str_postvars |
| 371 |
if_match str_queryvars |
| 372 |
if_modified_since unicode_errors |
| 373 |
if_none_match upath_info |
| 374 |
if_range url |
| 375 |
if_unmodified_since urlargs |
| 376 |
is_body_readable urlvars |
| 377 |
is_body_seekable uscript_name |
| 378 |
is_xhr user_agent |
| 379 |
make_body_seekable |
| 380 |
====================== ========================== |
| 381 |
|
| 382 |
And these are the specific ones from Pecan and the hook: |
| 383 |
|
| 384 |
* controller |
| 385 |
* hooks |
| 386 |
* params (params is actually available from `webob` but it is parsed |
| 387 |
by the hook for redability) |
| 388 |
|
| 389 |
Blacklisting Certain Paths |
| 390 |
.......................... |
| 391 |
|
| 392 |
Sometimes it's annoying to get information about *every* single |
| 393 |
request. To limit the output, pass the list of URL paths for which |
| 394 |
you do not want data as the ``blacklist``. |
| 395 |
|
| 396 |
The matching is done at the start of the URL path, so be careful when using |
| 397 |
this feature. For example, if you pass a configuration like this one:: |
| 398 |
|
| 399 |
{ 'blacklist': ['/f'] } |
| 400 |
|
| 401 |
It would not show *any* url that starts with ``f``, effectively behaving like |
| 402 |
a globbing regular expression (but not quite as powerful). |
| 403 |
|
| 404 |
For any number of blocking you may need, just add as many items as wanted:: |
| 405 |
|
| 406 |
{ 'blacklist' : ['/favicon.ico', '/javascript', '/images'] } |
| 407 |
|
| 408 |
Again, the ``blacklist`` key can be used along with the ``items`` key |
| 409 |
or not (it is not required). |