Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(media): add an example for using a custom JSON encoder #2035

Merged
merged 8 commits into from Mar 8, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/user/faq.rst
Expand Up @@ -915,6 +915,10 @@ Furthermore, different Internet media types such as YAML,
types than JSON, either as part of the respective (de)serialization format, or
via custom type extensions.

.. seealso:: See :class:`falcon.media.json.JSONHandler` for an exmaple on how to
maxking marked this conversation as resolved.
Show resolved Hide resolved
use a custom json encoder.


Does Falcon set Content-Length or do I need to do that explicitly?
------------------------------------------------------------------
Falcon will try to do this for you, based on the value of
Expand Down
31 changes: 31 additions & 0 deletions falcon/media/json.py
Expand Up @@ -94,6 +94,37 @@ class JSONHandler(BaseHandler):
),
)

You can also override the default JSONEncoder by using a custom Encoder and
updating the media handlers for ``application/json`` type to use that::

import json
from datetime import datetime
from functools import partial

import falcon
from falcon import media

class DatetimeEncoder(json.JSONEncoder):
\"\"\"Json Encoder that supports datetime objects.\"\"\"

def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
return super().default(obj)

app = falcon.App()

json_handler = media.JSONHandler(
dumps=partial(json.dumps, cls=DatetimeEncoder),
)
extra_handlers = {
'application/json': json_handler,
}

app.req_options.media_handlers.update(extra_handlers)
app.resp_options.media_handlers.update(extra_handlers)


Keyword Arguments:
dumps (func): Function to use when serializing JSON responses.
loads (func): Function to use when deserializing JSON requests.
Expand Down