Generating Atom feeds using Python and KID

The Atom syndication format is the standard way of making others aware of changes to your web-site, in particular to new content on the website. Atom is based on XML and Atom feeds can be produced very simply and conveniently using Kid and of course Python. Here is on outline on how to do it.

The Kid Template

The following is a sample Kid template:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:py="http://purl.org/kid/ns#">
  <id>http://www.bnikolic.co.uk/blog/blog</id>
  <title type="text">Bojan's Blog</title>
  <subtitle type="text">
  A blog on various computing related items by Bojan Nikolic. See
  http://www.bnikolic.co.uk/blog/index.html .
  </subtitle>

  <link href="http://www.bnikolic.co.uk/blog/blog.xml" rel="self"
        title="Bojan's blog feed"/>

  <updated py:content="mostrecent"></updated>

  <entry py:for="b in blist">
    <author>
     <name>Bojan Nikolic</name>
     <email>bojan@bnikolic.co.uk</email>
    </author>
    <updated py:content="b[3]">
    No date found
    </updated>

  <id py:content="'http://www.bnikolic.co.uk/blog/'+b[0]+'.html'"></id>

  <link py:attrs="href='http://www.bnikolic.co.uk/blog/'+b[0]+'.html'"/>

  <title type="text" py:content="b[1]">No title found</title>

  <summary type="html" xml:space="preserve" py:content="b[2]">
  No summary found
  </summary>

 </entry>

</feed>

Explanation:

The above template uses two python variables:

  • mostrecent which is a string containing the date of the most recent change to the website
  • blist which is a list of 4-tuples: ( post name, title, summary , date created/updated)

Invocation:

From python the kid template can be processed with something like:

def Kiddify(kid_fname,
            blist,
            fnameout,
            **kwargs):

    template=kid.Template(file=kid_fname,
                          blist=blist,
                          mostrecent=mostrecent,
                          **kwargs)
    fout=open(fnameout, "w")
    fout.write(template.serialize(output="xml"))

That is it! In the following article I give the full Python script to generate the Atom feed from a directory of text files.