Monday, June 27, 2011

Relearning Twisted.web

I want to use Twisted.web for some projects, and I haven't used it in years. I'm relearning and I feel like a novice all over again, as I should, given the years that have passed since I have seriously looked at any twisted code. I miss it, very much. Want to relearn or learn for the first time? I can't stress enough the excellence of a quick pass through the examples of Twisted.web in 60 Seconds. Go through those immediately. Afterwards, I read up on the new twisted.web.template, which is based on the Nevow templates I worked with so long-feeling ago, and I'm pretty happy with what I see there. I'm wondering how well it will produce HTML5 compliant markup, not that it is very strict, but it looks pretty clear.

My brain still thinks in asynchronous operations and I constantly have to unravel those thoughts and figure out how to express them, non-ideally, in a synchronous workflow. This is becoming tiring, and while I don't plan on leaving Django, I do plan on giving my brain a rest. Maybe I'll find a way to combine my two interests in the near future...

This is the result of the hour I spent relearning last night.

import time

from twisted.web.server import Site, NOT_DONE_YET
from twisted.web.static import File
from twisted.web.resource import Resource

from twisted.internet import reactor
from twisted.internet.defer import Deferred

class ClockPage(Resource):
    isLeaf = True
    def render_GET(self, request):
        d = Deferred()
        def _(r):
            request.write("<html><body>%s</body></html>" % (r,))

        def get_time(r):

        reactor.callLater(2, get_time, None)
        return NOT_DONE_YET

resource = ClockPage()
factory = Site(resource)
reactor.listenTCP(8888, factory)

No comments:

I write here about programming, how to program better, things I think are neat and are related to programming. I might write other things at my personal website.

I am happily employed by the excellent Caktus Group, located in beautiful and friendly Carrboro, NC, where I work with Python, Django, and Javascript.

Blog Archive