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()
@d.addCallback
def _(r):
request.write("<html><body>%s</body></html>" % (r,))
request.finish()
def get_time(r):
d.callback(time.ctime())
reactor.callLater(2, get_time, None)
return NOT_DONE_YET
resource = ClockPage()
factory = Site(resource)
reactor.listenTCP(8888, factory)
reactor.run()
Comments