I came across an Agile RSS Aggregator in Ruby which had very elegant code, so I decided to port it to Python. It uses wsgi, the Universal Feed Parser, and the Mako Template.
Here is the code:
#!/usr/bin/python
from wsgiref.simple_server import make_server
from mako.template import Template
import feedparser
class Feed:
""" A Python port of the "Agile RSS Aggregator in Ruby"
See README for details
"""
def __init__(self, environ, start_response):
self.environ = environ
self.start = start_response
def __iter__(self):
status = "200 OK"
response_headers = [('Content-type','text/html')]
self.start(status, response_headers)
stories = []
for f in open('feeds.txt', 'r'):
feed = feedparser.parse(f.strip())
stories.extend(feed.entries)
page = Template(filename='news.mako', output_encoding='utf8')
yield page.render(stories=stories)
httpd= make_server("", 8000, Feed)
httpd.serve_forever()
If you compare this to the Ruby version, you can see the striking resemblance of the code. Ruby and Python are very similar when it comes to doing simple things like this.
For comparison's sake, here is the relevant portion of the mako template:
% for item in stories:
<div class="section details">
<h3><a href="${item.link}">${item.title}</a></h3>
<p style="color:#444;font-size:90%;">${item.summary}</p>
</div>
% endfor
Again, very similar to the Erubis template the original version used. Technically, I could have used something like:
<% item.link %>
instead of :
${item.link}
which will make the code more similar, but I prefer the latter convention because it makes the template easier to read.
One caveat is with the wsgiref.simpleserver. I couldn't find a quick way to define the static directory ("files" in the original) to serve the css style sheet. The workaround was to put the style directly in the mako template, which admittedly is a bit annoying.
However, in a real world situation, chances are that we will be using an application framework like Pylons or TurboGears which will solve the problem, so I'm not going to dig too deeply into it. If anyone knows a simple way of exposing a filesystem directory in wsgi, please let me know!
Finally, here is the download link
0 コメント:
コメントを投稿