Skip to content

Instantly share code, notes, and snippets.

@akx
Created July 3, 2020 09:55
Show Gist options
  • Save akx/02d4881dbb6af32e1d92c2e097b4f3ff to your computer and use it in GitHub Desktop.
Save akx/02d4881dbb6af32e1d92c2e097b4f3ff to your computer and use it in GitHub Desktop.
import orjson
from rest_framework.utils import encoders
from rest_framework import renderers
json_default_encode = encoders.JSONEncoder().default
class ORJSONRenderer(renderers.JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
if data is None:
return bytes()
renderer_context = renderer_context or {}
indent = self.get_indent(accepted_media_type, renderer_context)
if not indent: # Indent not requested, fast path
try:
return orjson.dumps(data, default=json_default_encode)
except orjson.JSONEncodeError:
pass # Fall through to slower rendering
return super().render(data, accepted_media_type, renderer_context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment