[Twisted-web] nevow + ajax - lite

Tim Stebbing tjstebbing at gmail.com
Sat Jan 21 23:17:51 MST 2006

Just recently someone commented on how people where starting to write
form field validation using athena, I mean, talk about overkill. I've
been using something like this little snippet of code since about the
time athena got json.py added with great success to build
mochikit-using ajax UIs.

Athena rocks, but unless you actually want to receive server side
events, its usually overkill, things like field validation are a great
example of this. If you think hard about the type of app you're
writing its more often than not the common case not to be expecting
serverside events.

from twisted.internet.defer import maybeDeferred
from twisted.python import log
from nevow import rend, static, json

class AjaxResource(rend.Page):

    def childFactory(self, ctx, methodName):
        f = getattr(self, 'ajax_' + methodName, None)
        if f:
            d = maybeDeferred(f, ctx)
            d.addCallback(lambda r: static.Data(json.serialize(r),'text/html'))
            return d
        return json.serialize(u"Method not found")

this could be a mixin, but I usually just subclass it, you just add an
ajax_foo(self, ctx) method and call it from javascript using
mochikit's loadJSONDoc, inside your ajax_ method you access
inevow.IRequest(ctx).args to get any params. Perhaps some smart person
could make it extract the args and pass them to the method if they
liked. Its designed to be about as simple as you can get, I think
thats a good point.

hope this is useful for someone


More information about the Twisted-web mailing list