Files
deb-python-falcon/falcon/media/msgpack.py
John Vrbanac 3495344ff4 feat: Request and Response media-type handling (#1050)
This is a first pass at a non-breaking change that'll allow for a customizable media handling system. This approach combines many of the suggestions brought up by the community in #145.

One the thing that is left out of this PR is handling full content negotiation (i.e. connecting the request's accept header to the response's content-type). Unfortunately, this is a harder problem to solve in a backwards compatible fashion that doesn't affect performance. However, especially as we move towards v2, I think that would be a great opportunity to revisit full negotiation. In the meantime, there are several easy workarounds for people needing this functionality.

Closes #145
2017-06-14 23:38:47 -06:00

41 lines
1.1 KiB
Python

from __future__ import absolute_import
from falcon import errors
from falcon.media import BaseHandler
class MessagePackHandler(BaseHandler):
"""Handler built using the :py:mod:`msgpack` module from python-msgpack
Note:
This handler uses the `bin` type option which expects bytes instead
of strings.
Note:
This handler requires the ``python-msgpack`` package to be installed.
"""
def __init__(self):
import msgpack
self.msgpack = msgpack
self.packer = msgpack.Packer(
encoding='utf-8',
autoreset=True,
use_bin_type=True,
)
def deserialize(self, raw):
try:
# NOTE(jmvrbanac): Using unpackb since we would need to manage
# a buffer for Unpacker() which wouldn't gain us much.
return self.msgpack.unpackb(raw, encoding='utf-8')
except ValueError as err:
raise errors.HTTPBadRequest(
'Invalid MessagePack',
'Could not parse MessagePack body - {0}'.format(err)
)
def serialize(self, media):
return self.packer.pack(media)