A dictionary mapping media types to Codecs.
Keys should be media types as bytestrings, and values should be Codec subclasses (or at least match the decode/encode interface).
As an example, start by defining a codec:
>>> import simplejson
>>> class JSONCodec(Codec):
... def encode(media_type, obj, **params):
... return (media_type, simplejson.dumps(obj, **params))
... def decode(content_type, bytes):
... return simplejson.loads(bytes)
Create a register and add the codec to it:
>>> reg = CodecRegister()
>>> reg['application/json'] = JSONCodec
>>> reg['application/json'] is JSONCodec
True
You can then encode and decode objects using the same method signatures as on individual codecs. The codec register will dispatch based on the media type provided:
>>> reg.encode('application/json', {"a": 1})
('application/json', '{"a": 1}')
>>> reg.encode('application/json', {"a": 1}, indent=True)
('application/json', '{\n "a": 1\n}')
>>> reg.decode('application/json', '{"a": 1}')
{'a': 1}
Since full media types can be rather unwieldy, you can also register shorter aliases which will be resolved to their full counterparts first:
>>> reg.alias('json', 'application/json')
>>> reg.encode('json', {"a": 1})
('application/json', '{"a": 1}')
Note that this only applies to encoding; for decoding, it’s assumed that full content type headers will be provided. If an alias is used as the content type for a decode, a KeyError will be raised:
>>> reg.decode('json', '{"a": 1}')
Traceback (most recent call last):
...
KeyError: 'json'
A superclass for implementing codecs.
This class should be considered abstract (encode() and decode() are unimplemented), but it has a metaclass which will make those methods static.
Example:
>>> import simplejson
>>> class JSONCodec(Codec):
... def encode(media_type, obj, **params):
... return (media_type, simplejson.dumps(obj, **params))
... def decode(content_type, bytes):
... return simplejson.loads(bytes)
>>> JSONCodec.encode('application/json', {"a": 1})
('application/json', '{"a": 1}')
>>> JSONCodec.decode('application/json', '{"a": 1}')
{'a': 1}
Note that encode() and decode() do not take self; the metaclass will make them static methods automatically. This allows you to register the classes directly on a CodecRegister.
Decode a bytestring to a Python object, given its content-type.
Parameters: |
|
---|---|
Returns: | A Python object. |
Encode a Python object into the given media type.
Parameters: |
|
---|---|
Params : | Any additional parameters for the encoder. |
Returns: | A two-tuple of (content_type, bytes), where content_type should be a str of the full Content-Type header (including parameters) and bytes a str of the encoded output. |