Using django-debug-toolbar with Piston

I was trying out Piston to build an API for my Django app. I wrote a simple REST URL to return all of the 399 records in my database, encoded as JSON.

To my surprise, it was taking 11 seconds. I wondered whether I was doing something horrendous in SQL. I normally rely on django-debug-toolbar to tell me these things, but debug-toolbar injects itself into an HTML page. With my API returning JSON, it wasn’t going to work.

Now Piston supports a variety of formats: JSON, XML, YAML, and so on. It does so via what it calls emitters, which are classes that implement the encoding of your return data. Since I needed HTML for debug-toolbar, I hacked up an HTML emitter:

from piston.emitters import Emitter
from django.http import HttpResponse
from django.utils import simplejson
# thanks to marteinn_se for this bit (see comments)
from django.core.serializers.json import DateTimeAwareJSONEncoder

class HTMLEmitter( Emitter ):
    def render( self, request ):
        data = self.construct()
        json_dump = simplejson.dumps(data, cls=DateTimeAwareJSONEncoder, ensure_ascii=False, indent=4)
        return HttpResponse('' % json_dump)

Emitter.register('html', HTMLEmitter, 'text/html')

Then after following the instructions on how to edit my to use the emitter, I went to a REST URL in the browser, and there was the debug toolbar, telling me that it spent 300ms in SQL and that I was going to have to look elsewhere for the other 10700ms. (*)

By the way – if you try this and you get an exception about __name__, that’s because of a bug in the 0.85 version of the debug-toolbar (the latest release at the time of writing). It’s been resolved in the debug-toolbar trunk, which you can fetch and install with

git clone django-debug-toolbarpython install

(*) P.S. The slowness is down to fetching data out of the database. Through judicious use of the QuerySet methods values_list() and select_related() I’ve halved the time taken. Still much too slow, but getting there…

1 comment
  1. marteinn_se said:

    Hi! Just wanted to say that I noticed a bug with the standard json.dump method and the datetime model fields.So I rewrote the htmlemitter a little (so it works just like pistons json emitter). post!/ M

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: