Last active
March 4, 2020 13:40
-
-
Save zarinpy/ab5d9edc00ef3a60df907e4ccc864c2f to your computer and use it in GitHub Desktop.
custom renderer for DRF
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomRenderer(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) | |
new_data = { # new expose | |
'code': None, | |
'message': '', | |
'data': {}, | |
} | |
if indent is None: | |
separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS | |
else: | |
separators = INDENT_SEPARATORS | |
if 'code' in renderer_context['kwargs'].keys(): | |
new_data['code'] = renderer_context['kwargs']['code'] | |
else: | |
new_data['code'] = renderer_context['response'].status_code | |
if 'message' in renderer_context['kwargs'].keys(): | |
new_data['message'] = renderer_context['kwargs']['message'] | |
new_data['data'] = data | |
ret = json.dumps( | |
new_data, cls=self.encoder_class, | |
indent=indent, ensure_ascii=self.ensure_ascii, | |
allow_nan=not self.strict, separators=separators | |
) | |
if isinstance(ret, six.text_type): | |
ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029') | |
return bytes(ret.encode('utf-8')) | |
return ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
you can send kwargs to this section by set the
self.get_renderer_context()['kwargs']['key']