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
31 changes: 31 additions & 0 deletions falcon/media/json.py
Expand Up @@ -94,6 +94,37 @@ class JSONHandler(BaseHandler):
),
)

You can also override the JSONEncoder used by using a custom Encoder by
vytas7 marked this conversation as resolved.
Show resolved Hide resolved
updating the media handlers for ``application/json`` type::

import json
from datetime import datetime
from functools import partial

import falcon
from falcon import meda

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

def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
super().default(obj)
maxking marked this conversation as resolved.
Show resolved Hide resolved

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