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
23 lines
594 B
Python
23 lines
594 B
Python
from __future__ import absolute_import
|
|
|
|
import json
|
|
|
|
from falcon import errors
|
|
from falcon.media import BaseHandler
|
|
|
|
|
|
class JSONHandler(BaseHandler):
|
|
"""Handler built using Python's :py:mod:`json` module."""
|
|
|
|
def deserialize(self, raw):
|
|
try:
|
|
return json.loads(raw.decode('utf-8'))
|
|
except ValueError as err:
|
|
raise errors.HTTPBadRequest(
|
|
'Invalid JSON',
|
|
'Could not parse JSON body - {0}'.format(err)
|
|
)
|
|
|
|
def serialize(self, media):
|
|
return json.dumps(media, ensure_ascii=False).encode('utf-8')
|