Response handlers are used by Controllers to transform the return value from an action (such as a string, int, etc.) into a suitable webapp2.Response. They provide the convenience of not having to repeat the same code over and over. Ferris provides a couple of built-in response handlers and allows you to register your own.
Simply return a value from a controller’s action:
@route def test(self): return "Hello!"
By returning a string Ferris skips the view and uses whichever response handler is defined for that particular type.
- class ferris.core.response_handlers.StringResponseHandler¶
Simply makes the string the body of the response.
- class ferris.core.response_handlers.IntResponseHandler¶
Returns a response with the specified http status code, for example:
Will cause a 404 Not Found error response.
It’s possible to create new response handlers to handle any type. Simply subclass ResponseHandler like so:
from ferris.core.response_handlers import ResponseHandler from webapp2 import Response class WidgetResponseHandler(ResponseHandler): type = Widget # The class that this response handler will deal with. # This function is responsible for returning a webapp2.Response def process(self, controller, result): response = Response() response.body = result.info return response
Be sure to import this in your controller or in one of the bootstrapping scripts (app/routes.py or app/listeners.py) to make sure they’re picked up by Ferris.
If you want to preserve the existing response then modify controller.response instead of creating a new one. This preserves headers and other stuff (such as client side caching):
controller._clear_redirect() controller.response.body = result.info return controller.response