Implementing RSS in Pylons
I needed a RSS feed for this blog. A quick Google search revealed the library PyRSS2Gen which seemed to be an easy option for what I was trying to do.
I use Pylons for most projects these days. So this article will show you how to implement a simple and fast RSS feed in that framework.
I start by adding the route I want for the feed to config/routing.py.
EDIT: It's nice to have a url() alias for routes you will be linking, so I added it as the first parameter in connect for this example.
map.connect('rss', '/feed/rss', controller="posts", action="rss_feed")
That will map http://kyleterry.com/feed/rss to my posts controller and dispatch to the rss_feed action.
Now that I have my route, I need to edit controllers/posts.py and import PyRSS2Gen as rss and datetime.
import PyRSS2Gen as rss
import datetime
I now get to create the rss_feed action. In this action I will be loading the posts from the database using SqlAlchemy, creating an RSS item for each one, and finally creating then returning the XML from the PyRSS2Gen.RSS2 object.
def rss_feed(self):
post_q = model.meta.Session.query(model.Post)\
.limit(10)
posts = post_q.all()
items = []
for post in posts:
items.append(
rss.RSSItem(
title=post.title,
link='http://kyleterry.com%s' % \
h.url_for('post', id=post.id),
description=h.markdown(post.body),
guid='http://kyleterry.com%s' % \
h.url_for('post', id=post.id),
pubDate=post.posted
)
)
feed = rss.RSS2(
title='Kyle Terry - Latest Entries',
link='http://kyleterry.com',
description='A vegan software developer',
lastBuildDate=datetime.datetime.now(),
items=items
)
return feed.to_xml()
The .to_xml() method will just return the rendered XML as a string. If you need to write this output to a file, you can use the .write_xml() method which is documented on the PyRSS2Gen website linked above.