我的博客有一个 Atom 提要生成器,它在 AppEngine/Python 上运行。我使用 Django 1.2 模板引擎来构建提要。我的模板如下所示:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xml:lang="en"
xml:base="http://www.example.org">
<id>urn:uuid:4FC292A4-C69C-4126-A9E5-4C65B6566E05</id>
<title>Adam Crossland's Blog</title>
<subtitle>opinions and rants on software and...things</subtitle>
<updated>{{ updated }}</updated>
<author>
<name>Adam Crossland</name>
<email>adam@adamcrossland.net</email>
</author>
<link href="http://blog.adamcrossland.net/" />
<link rel="self" href="http://blog.adamcrossland.net/home/feed" />
{% for each_post in posts %}{{ each_post.to_atom|safe }}
{% endfor %}
</feed>
注意:如果您使用其中任何一个,您需要创建自己的 uuid 才能进入 id 节点。
更新的节点应包含提要内容最后更新为rfc 3339 格式的时间和日期。幸运的是,Python 有一个库可以为您解决这个问题。生成提要的控制器的摘录:
from rfc3339 import rfc3339
posts = Post.get_all_posts()
self.context['posts'] = posts
# Initially, we'll assume that there are no posts in the blog and provide
# an empty date.
self.context['updated'] = ""
if posts is not None and len(posts) > 0:
# But there are posts, so we will pick the most recent one to get a good
# value for updated.
self.context['updated'] = rfc3339(posts[0].updated(), utc=True)
response.content_type = "application/atom+xml"
不要担心self.context['updated'] 的东西。这就是我的框架如何提供设置模板变量的快捷方式。导入部分是我使用rfc3339 函数对我想使用的日期进行编码。另外,我将 Response 对象的content_type 属性设置为application/atom+xml。
唯一缺少的部分是模板使用了一个名为to_atom 的方法将Post 对象转换为Atom 格式的数据:
def to_atom(self):
"Create an ATOM entry block to represent this Post."
from rfc3339 import rfc3339
url_for = self.url_for()
atom_out = "<entry>\n\t<title>%s</title>\n\t<link href=\"http://blog.adamcrossland.net/%s\" />\n\t<id>%s</id>\n\t<summary>%s</summary>\n\t<updated>%s</updated>\n </entry>" % (self.title, url_for, self.slug_text, self.summary_for(), rfc3339(self.updated(), utc=True))
return atom_out
据我所知,这就是所需的全部内容,并且此代码确实为我的博客生成了一个完美且有效的提要。现在,如果你真的想做 RSS 而不是 Atom,你需要改变 feed 模板、Post 模板和 content_type 的格式,但我认为这是获取 feed 所需要做的事情的本质从 AppEngine/Python 应用程序生成。