API Documentation

Content Type Handling

class sprockets.mixins.mediatype.content.ContentMixin[source]

Mix this in to add some content handling methods.

class MyHandler(ContentMixin, web.RequestHandler):
   def post(self):
      body = self.get_request_body()
      # do stuff --> response_dict
      self.send_response(response_dict)

get_request_body() will deserialize the request data into a dictionary based on the Content-Type request header. Similarly, send_response() takes a dictionary, serializes it based on the Accept request header and the application ContentSettings, and writes it out, using self.write().

get_request_body()[source]

Fetch (and cache) the request body as a dictionary.

Raises

web.HTTPError

  • if the content type cannot be matched, then the status code is set to 415 Unsupported Media Type.

  • if decoding the content body fails, then the status code is set to 400 Bad Syntax.

get_response_content_type()[source]

Figure out what content type will be used in the response.

send_response(body, set_content_type=True)[source]

Serialize and send body in the response.

Parameters
  • body (dict) – the body to serialize

  • set_content_type (bool) – should the Content-Type header be set? Defaults to True

Content Type Registration

sprockets.mixins.mediatype.content.install(application, default_content_type, encoding=None)[source]

Install the media type management settings.

Parameters
Returns

the content settings instance

Return type

sprockets.mixins.mediatype.content.ContentSettings

sprockets.mixins.mediatype.content.get_settings(application, force_instance=False)[source]

Retrieve the media type settings for a application.

Parameters
Returns

the content settings instance

Return type

sprockets.mixins.mediatype.content.ContentSettings

sprockets.mixins.mediatype.content.set_default_content_type(application, content_type, encoding=None)[source]

Store the default content type for an application.

Parameters
  • application (tornado.web.Application) – the application to modify

  • content_type (str) – the content type to default to

  • encoding (str|None) – encoding to use when one is unspecified

sprockets.mixins.mediatype.content.add_binary_content_type(application, content_type, pack, unpack)[source]

Add handler for a binary content type.

Parameters
  • application (tornado.web.Application) – the application to modify

  • content_type (str) – the content type to add

  • pack – function that packs a dictionary to a byte string. pack(dict) -> bytes

  • unpack – function that takes a byte string and returns a dictionary. unpack(bytes) -> dict

sprockets.mixins.mediatype.content.add_text_content_type(application, content_type, default_encoding, dumps, loads)[source]

Add handler for a text content type.

Parameters
  • application (tornado.web.Application) – the application to modify

  • content_type (str) – the content type to add

  • default_encoding (str) – encoding to use when one is unspecified

  • dumps – function that dumps a dictionary to a string. dumps(dict, encoding:str) -> str

  • loads – function that loads a dictionary from a string. loads(str, encoding:str) -> dict

Note that the charset parameter is stripped from content_type if it is present.

sprockets.mixins.mediatype.content.add_transcoder(application, transcoder, content_type=None)[source]

Register a transcoder for a specific content type.

Parameters
  • application (tornado.web.Application) – the application to modify

  • transcoder – object that translates between bytes and object instances

  • content_type (str) – the content type to add. If this is unspecified or None, then the transcoder’s content_type attribute is used.

The transcoder instance is required to implement the following simple protocol:

transcoder.content_type

str that identifies the MIME type that the transcoder implements.

transcoder.to_bytes(inst_data, encoding=None)bytes
Parameters
  • inst_data (object) – the object to encode

  • encoding (str) – character encoding to apply or None

Returns

the encoded bytes instance

transcoder.from_bytes(data_bytes, encoding=None)object
Parameters
  • data_bytes (bytes) – the bytes instance to decode

  • encoding (str) – character encoding to use or None

Returns

the decoded object instance

class sprockets.mixins.mediatype.content.ContentSettings[source]

Content selection settings.

An instance of this class is stashed in application.settings under the SETTINGS_KEY key. Instead of creating an instance of this class yourself, use the install() function to install it into the application.

The settings instance contains the list of available content types and handlers associated with them. Each handler implements a simple interface:

  • to_bytes(dict, encoding:str) -> bytes

  • from_bytes(bytes, encoding:str) -> dict

Use the add_binary_content_type() and add_text_content_type() helper functions to modify the settings for the application.

This class acts as a mapping from content-type string to the appropriate handler instance. Add new content types and find handlers using the common dict syntax:

class SomeHandler(web.RequestHandler):

   def get(self):
      settings = ContentSettings.get_settings(self.application)
      response_body = settings['application/msgpack'].to_bytes(
         response_dict, encoding='utf-8')
      self.write(response_body)

def make_application():
   app = web.Application([('/', SomeHandler)])
   add_binary_content_type(app, 'application/msgpack',
                           msgpack.packb, msgpack.unpackb)
   add_text_content_type(app, 'application/json', 'utf-8',
                         json.dumps, json.loads)
   return app

Of course, that is quite tedious, so use the ContentMixin instead.

property available_content_types

List of the content types that are registered.

This is a sequence of ietfparse.datastructures.ContentType instances.

Bundled Transcoders

class sprockets.mixins.mediatype.transcoders.JSONTranscoder(content_type='application/json', default_encoding='utf-8')[source]

JSON transcoder instance.

Parameters
  • content_type (str) – the content type that this encoder instance implements. If omitted, application/json is used. This is passed directly to the TextContentHandler initializer.

  • default_encoding (str) – the encoding to use if none is specified. If omitted, this defaults to utf-8. This is passed directly to the TextContentHandler initializer.

This JSON encoder uses json.loads() and json.dumps() to implement JSON encoding/decoding. The dump_object() method is configured to handle types that the standard JSON module does not support.

dump_options

Keyword parameters that are passed to json.dumps() when dumps() is called. By default, the dump_object() method is enabled as the default object hook.

load_options

Keyword parameters that are passed to json.loads() when loads() is called.

dump_object(obj)[source]

Called to encode unrecognized object.

Parameters

obj (object) – the object to encode

Returns

the encoded object

Raises

TypeError – when obj cannot be encoded

This method is passed as the default keyword parameter to json.dumps(). It provides default representations for a number of Python language/standard library types.

Python Type

String Format

bytes, bytearray, memoryview

Base64 encoded string.

datetime.datetime

ISO8601 formatted timestamp in the extended format including separators, milliseconds, and the timezone designator.

uuid.UUID

Same as str(value)

dumps(obj)[source]

Dump a object instance into a JSON str

Parameters

obj (object) – the object to dump

Returns

the JSON representation of object

loads(str_repr)[source]

Transform str into an object instance.

Parameters

str_repr (str) – the UNICODE representation of an object

Returns

the decoded object representation

class sprockets.mixins.mediatype.transcoders.MsgPackTranscoder(content_type='application/msgpack')[source]

Msgpack Transcoder instance.

Parameters

content_type (str) – the content type that this encoder instance implements. If omitted, application/msgpack is used. This is passed directly to the BinaryContentHandler initializer.

This transcoder uses the umsgpack library to encode and decode objects according to the msgpack format.

normalize_datum(datum)[source]

Convert datum into something that umsgpack likes.

Parameters

datum – something that we want to process with umsgpack

Returns

a packable version of datum

Raises

TypeError – if datum cannot be packed

This message is called by packb() to recursively normalize an input value before passing it to umsgpack.packb(). Values are normalized according to the following table.

Value

MsgPack Family

None

nil byte (0xC0)

True

true byte (0xC3)

False

false byte (0xC2)

int

integer family

float

float family

String

str family

bytes

bin family

bytearray

bin family

memoryview

bin family

collections.abc.Sequence

array family

collections.abc.Set

array family

collections.abc.Mapping

map family

uuid.UUID

Converted to String

packb(data)[source]

Pack data into a bytes instance.

unpackb(data)[source]

Unpack a object from a bytes instance.