Handles Content-Type & Accept header serialization and deserialization for you
Find a file
2015-08-20 07:12:26 -04:00
docs Clean up documentation. 2015-08-20 07:12:26 -04:00
requires Clean up documentation. 2015-08-20 07:12:26 -04:00
sprockets Add response type negotiation. 2015-08-19 18:29:11 -04:00
.gitignore Initial commit 2015-06-09 09:28:29 -04:00
.travis.yml Fix up badges a bit 2015-06-09 09:42:21 -04:00
examples.py Implement basic content handling framework. 2015-08-19 17:53:46 -04:00
LICENSE Initial commit 2015-06-09 09:28:29 -04:00
MANIFEST.in RST 2015-08-07 17:14:37 -04:00
README.rst Clean up documentation. 2015-08-20 07:12:26 -04:00
setup.cfg Update setup.cfg to include coverage 2015-06-09 10:29:35 -04:00
setup.py RST 2015-08-07 17:14:37 -04:00
tests.py Add response type negotiation. 2015-08-19 18:29:11 -04:00

sprockets.mixins.media_type
===========================
A mixin that performs Content-Type negotiation and request/response
(de)serialization.

This mix-in adds two methods to a ``tornado.web.RequestHandler`` instance:

- ``get_request_body() -> dict``: deserializes the request body according
  to the HTTP ``Content-Type`` header and returns the deserialized body.
- ``send_response(object)``: serializes the response into the content type
  requested by the ``Accept`` header.

Support for a content types is enabled by calling either the
``add_binary_content_type`` or ``add_text_content_type`` function with the
``tornado.web.Application`` instance, the content type, encoding and decoding
functions as parameters:

.. code-block:: python

   import json

   from sprockets.mixins import media_type
   from tornado import web

   def make_application():
       application = web.Application([
           # insert your handlers here
       ])

       media_type.add_text_content_type(application,
                                        'application/json', 'utf-8',
                                        json.dumps, json.loads)

       return application

The *add content type* functions will add a attribute to the ``Application``
instance that the mix-in uses to manipulate the request and response bodies.

.. code-block:: python

   from sprockets.mixins import media_type
   from tornado import web

   class SomeHandler(media_type.ContentMixin, web.RequestHandler):
       def get(self):
           self.send_response({'data': 'value'})
           self.finish()

       def post(self):
           body = self.get_request_body()
           # do whatever
           self.send_response({'action': 'performed'})
           self.finish()

Based on the settings stored in the ``Application`` instance and the HTTP
headers, the request and response data will be handled correctly or the
appropriate HTTP exceptions will be raised.