This post originated from an RSS feed registered with Python Buzz
by Andrew Gross.
Original Post: Simple AJAX With Nevow's LivePage
Feed Title: argv0.net
Feed URL: http://www.pycs.net/users/0000445/weblog/rss.xml
Feed Description: a python programming journal by Andrew R. Gross
I spent the weekend without an net connection and with a few free hours without much to do, so I played around with Nevow's LivePage, which enables one to write so-called "AJAX" (Asyncronous Javascript And XmlHttpRequest) web applications. Like most else with Nevow, it's ridiculously easy to do. I wrote a simple app that lets the user enter an RSS url and get a 'slideshow' of items from that feed (using the FeedParser module to parse the RSS). It's nothing special at all, but it serves as decent boilerplate for an AJAX page, and it was short enough that I figured I'd post it here as an example.
classAjaxRSS(livepage.LivePage):addSlash=True@livepage.handler(byId('input').value)defselectFeed(client,feedUrl):defupdateClient(parsedFeed):ifparsedFeed['entries']:entry=parsedFeed['entries'][0]parsedFeed['entries']=parsedFeed['entries'][1:]client.set("link",T.a(href=entry['link'])[entry['title']])client.set("content",T.p()[loaders.htmlstr(entry['summary'])])reactor.callLater(5,updateClient,parsedFeed)d=getPage(feedUrl)d.addCallback(parse).addCallback(updateClient)docFactory=loaders.stan(T.html[T.head[livepage.glue],T.body[T.p["Enter an RSS url"],T.div(id="main")[T.form(id="form",onsubmit=selectFeed)[T.input(id="input",width="20"),T.input(type="submit",value="submit")]],T.div(id="post")[T.a(id="link"),T.br,T.p(id="content")]]])
Live demo here. Try http://flickr.com/services/feeds/photos_public.gne?tags=cats&format=rss_200 as a url, for a slideshow of people's cat pictures on Flickr
The magic here is the @livepage.handler(byId('input').value) decorator, which basically says "pass me the value of the node with the id of 'input'". Within the handler, we call the 'set' method on the client, which allows us to change the contents of the users HTML page (another useful client method is sendScript, which allows you to send a chunk of Javascript for immediate evaluation to the user's browser.
Here's the source, and a .tac file that you can launch with twistd -noy ajaxrss.tac