Skip to content

Instantly share code, notes, and snippets.

@zaki-yama
Created March 31, 2015 17:24
Show Gist options
  • Select an option

  • Save zaki-yama/86fe5f5250bf918ac7b0 to your computer and use it in GitHub Desktop.

Select an option

Save zaki-yama/86fe5f5250bf918ac7b0 to your computer and use it in GitHub Desktop.
DjangoでREST APIを作るためのmixinクラス
# -*- coding: utf-8 -*-
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
class JSONResponseMixin(object):
"""
A mixin that can be used to render a JSON response.
"""
response_class = HttpResponse
def render_to_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
response_kwargs['content_type'] = 'application/json'
return self.response_class(
self.convert_context_to_json(context),
**response_kwargs
)
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return json.dumps(context, cls=DjangoJSONEncoder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment