牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Django で json の出力メモ

create project, app

$ django-admin.py startproject app
$ cd app
$ python manage.py startapp blog

app/

settings.py

データベースの設定とか適当に

apps/urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^blog/', include('blog.urls')),
)

blog/

blog/views.py
from django import http
from django.utils import simplejson as json
from django.views.generic.base import View


class JSONResponseMixin(object):

    def render_to_response(self, context):
        "Returns a JSON response containing 'context' as payload"
        return self.get_json_response(self.convert_context_to_json(context))

    def get_json_response(self, content, **httpresponse_kwargs):
        "Construct an `HttpResponse` object."
        return http.HttpResponse(content,
                                 content_type='application/json',
                                 **httpresponse_kwargs)

    def convert_context_to_json(self, context):
        "Convert the context dictionary into a JSON object"
        return json.dumps(context)


class JSONView(JSONResponseMixin, View):
    pass


class FooView(JSONView):

    def get(self, request, *args, **kwargs):
        return self.render_to_response({'Foo': 'bar'})
urls.py
from django.conf.urls.defaults import patterns, url
from blog.views import FooView

urlpatterns = patterns('',
                       url(r'^foo$', FooView.as_view(), name='foo'),
                       )

確認

runserver
python manage.py runserver
curl
$ curl -D - http://127.0.0.1:8000/blog/foo
HTTP/1.0 200 OK
Date: Tue, 14 Aug 2012 12:05:02 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Type: application/json

{"Foo": "bar"}