Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / web / examples / lj.rpy.py
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 """
5 The example gets RSS feeds from LiveJournal users.  It demonstrates how to use
6 chained Deferred callbacks.
7
8 To test the script, rename the file to lj.rpy, and move it to any directory,
9 let's say /var/www/html/.
10
11 Now, start your Twisted web server:
12     $ twistd -n web --path /var/www/html/
13
14 And visit a URL like http://127.0.0.1:8080/lj.rpy?user=foo with a web browser,
15 replacing "foo" with a valid LiveJournal username.
16 """
17
18 from twisted.web import resource as resourcelib
19 from twisted.web import client, microdom, domhelpers, server
20
21 urlTemplate = 'http://%s.livejournal.com/data/rss'
22
23 class LJSyndicatingResource(resourcelib.Resource):
24
25     def render_GET(self, request):
26         """
27         Get an xml feed from LiveJournal and construct a new HTML page using the
28         'title' and 'link' parsed from the xml document.
29         """
30         url = urlTemplate % request.args['user'][0]
31         client.getPage(url, timeout=30).addCallback(
32         microdom.parseString).addCallback(
33         lambda t: domhelpers.findNodesNamed(t, 'item')).addCallback(
34         lambda itms: zip([domhelpers.findNodesNamed(x, 'title')[0]
35                                                                for x in itms],
36                          [domhelpers.findNodesNamed(x, 'link')[0]
37                                                                for x in itms]
38                         )).addCallback(
39         lambda itms: '<html><head></head><body><ul>%s</ul></body></html>' %
40                           '\n'.join(
41                ['<li><a href="%s">%s</a></li>' % (
42                   domhelpers.getNodeText(link), domhelpers.getNodeText(title))
43                        for (title, link) in itms])
44         ).addCallback(lambda s: (request.write(s),request.finish())).addErrback(
45         lambda e: (request.write('Error: %s' % e),request.finish()))
46         return server.NOT_DONE_YET
47
48 resource = LJSyndicatingResource()