Skip to content

Instantly share code, notes, and snippets.

@yarysh
Created May 7, 2013 10:00
Show Gist options
  • Select an option

  • Save yarysh/5531565 to your computer and use it in GitHub Desktop.

Select an option

Save yarysh/5531565 to your computer and use it in GitHub Desktop.
JSON response mixin for Django CBV.
#!/usr/bin/python
# coding: utf-8
import json
class JSONResponseMixin(object):
"""
A mixin that can be used to render a JSON response.
"""
def dateHandler(self, obj):
return obj.isoformat() if hasattr(obj, 'isoformat') else obj
def convertToJson(self, response):
return json.dumps(response, ensure_ascii=False,
default=self.dateHandler)
def jsonResponse(self, response, **response_kwargs):
response_kwargs['content_type'] = 'application/json'
return self.response_class(self.convertToJson(response),
**response_kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment