Skip to content Skip to sidebar Skip to footer

Access The Response Object In A Bottlepy After_request Hook

I have the following web app: import bottle app = bottle.Bottle() @app.route('/ping') def ping(): print 'pong' return 'pong' @app.hook('after_request') def after(): p

Solution 1:

Is there a way to access the response body before sending the response back?

You could write a simple plugin, which (depending on what you're actually trying to do with the response) might be all you need.

Here's an example from the Bottle plugin docs, which sets a request header. It could just as easily manipulate body.

from bottle import response, install
import time

defstopwatch(callback):
    defwrapper(*args, **kwargs):
        start = time.time()
        body = callback(*args, **kwargs)
        end = time.time()
        response.headers['X-Exec-Time'] = str(end - start)
        return body
    return wrapper

install(stopwatch)

Hope that works for your purposes.

Solution 2:

You can use plugin approach, this is what i did

from bottle import response


classBottlePlugin(object):

    name = 'my_custom_plugin'
    api = 2def__init__(self, debug=False):
        self.debug = debug
        self.app = Nonedefsetup(self, app):
        """Handle plugin install"""
        self.app = app

    defapply(self, callback):
        """Handle route callbacks"""defwrapper(*a, **ka):
            """Encapsulate the result in the expected api structure"""# Check if the client wants a different format# output depends what you are returning from view# in my case its dict with keys ("data")
            output = callback(*a, **ka)
            data = output["data"]
            paging = output.get("paging", {})

            response_data = {
                data: data,
                paging: paging
            }
            # in case if you want to update response# e.g response code
            response.status = 200return response_data

        return wrapper

Post a Comment for "Access The Response Object In A Bottlepy After_request Hook"