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
urls.py 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 https://github.com/django-debug-toolbar/django-debug-toolbarcd django-debug-toolbarpython setup.py install
(*) P.S. The slowness is down to fetching data out of the database. Through judicious use of the
select_related() I’ve halved the time taken. Still much too slow, but getting there…