Files
deb-python-falcon/doc/api/hooks.rst
Kurt Griffiths 6beba38df1 doc(guide): Improve and correct the prose across several documentation pages
Edit the prose in the existing documentation for clarity and correctness.

Closes #296
2015-01-22 17:12:48 -06:00

1.4 KiB

Hooks

Falcon supports both before and after hooks. You install a hook simply by applying one of the decorators below, either to an individual responder or to an entire resource.

For example, consider this hook that validates a POST request for an image resource:

def validate_image_type(req, resp, resource, params):
    if req.content_type not in ALLOWED_IMAGE_TYPES:
        msg = 'Image type not allowed. Must be PNG, JPEG, or GIF'
        raise falcon.HTTPBadRequest('Bad request', msg)

You would attach this hook to an on_post responder like so:

@falcon.before(validate_image_type)
def on_post(self, req, resp):
    pass

Or, suppose you had a hook that you would like to apply to all responders for a given resource. In that case, you would simply decorate the resource class:

@falcon.before(extract_project_id)
class Message(object):
    def on_post(self, req, resp):
        pass

    def on_get(self, req, resp):
        pass

Falcon middleware components can also be used to insert logic before and after requests. Unlike hooks, however, middleware components are triggered globally for all requests. This feature is documented in the API class <api> reference and the Quickstart <quickstart-more-features> example code.

falcon