mengu on web programming.

Generating RSS Feeds With WebPy

Some days ago I have seen someone asking how to generate RSS feeds with webpy. It is like generating feeds with any other web framework.

How the logic should be?

  • Retrieve the items from the database.
  • Create a RSS template.
  • Set the content type.
  • Print the items via template.

So, let's start with creating our feed class first.

class feed:
    def GET(self):
        date = datetime.today().strftime("%a, %d %b %Y %H:%M:%S +0200")
        posts = db.select("post", order="id DESC", limit=10)
        web.header('Content-Type', 'application/xml')
        return render.feed(posts=posts, date=date)

This is all we need for generating for the feed. Now we can skip to create the feed template.

<?xml version="1.0"?>
<rss version="2.0">
   <channel>
      <title>Mengu.net RSS Feed</title>
      <link>http://www.mengu.net/</link>
      <description>mengu on web programming.</description>
      <language>en-us</language>
      <pubDate>{{ date }}</pubDate>

      <lastBuildDate>{{ date }}</lastBuildDate>
      <generator>Mengu.net</generator>
      <managingEditor>mengu@mengu.net</managingEditor>
      <webMaster>mengu@mengu.net</webMaster>

      {% for post in posts %}
      <item>
         <title>{{ post.title }}</title>
         <link>http://www.mengu.net/post/{{ post.slug }}</link>
         <description><![CDATA[{{ post.body[:100] }}..]]></description>
         <pubDate>{{ post.dateline }}</pubDate>
         <guid>http://www.mengu.net/post/{{ post.dateline }}</guid>
      </item>
      {% endfor %}
    </channel>
</rss>

This is a valid RSS feed. You can learn more on RSS feeds here. So, basically I have created a valid RSS template and then loop through the post items and I have my RSS working perfect.

Enjoy!

Comments

Ken said on 05/02/2010 08:56 AM

front of the render, it needs: web.header('Content-Type', 'application/xml')


Mengu Kagan said on 05/02/2010 19:25 PM

Thank you Ken. I forgot changing the content type. It's needed because if it's going to be a valid RSS feed, the content type should be application/xml.


Leave a Response

Name*:
E-Mail* (not published):
Web site:
Response: