1. 准备工作
如果一点儿都不了解rss或者atom,或者不是很了解这两者的xml里各个字段什么意思以及各有什么值,可以看看w3schools的资料,rss见XML RSS,atom见Introduction to Atom。其实就是类似sitemap,把博客中的最新的部分动态、文章的信息按照一定规范更新到xml中,方便订阅者及时获取。
所以可以选择自己按照上述文档配合render_template和模板语言生成。
当然了,本次用工具python-feedgen来生成
安装
pip3 install feedgen
2. 添加feed信息
然后准备好10个或20个最新的博客内容动态,包括每条动态的标题、简介(或者完整内容)、发布时间、作者(这个一般不太需要)。
因为博客首页一般都有有类似的时间线展示,所以很容易可以收集到,然后按照包的文档进行方法调用。
如果你比较熟悉rss或者不太想了解个别细节可以直接跳过
- fg.id是给atom用的,如果有一个长期使用的域名的话就填域名就好了
- fg.title对应的也就是rss xml里channel中的title
- 因为要同时生成rss和atom两种xml,所以调用fg.link的时候,href带有atom.xml后缀的要先调用,否则生成出来的rss xml中image里的link可就不是指向博客首页了
- fg.subtitle就是博客的简介
- 随后开始为具体内容进行添加。如果传递进来的数组是按照时间由新到旧排列的,要进行reverse(),生成出来的xml里才是最新的在前面
- fe是item的实例。把具体某篇博文的标题、简介或者内容、分类填入。分类填入的是字典,具体字段见此
- fe.id(url)和fe.link(url)填入的是这篇博文的url链接,前者为atom使用,后者为rss使用
- 最后把文章的发布时间填入fe.pubDate,这里要注意的是,必须要传递datetime.datetime类型的值,且必须要带有tzinfo,下列给出了示范
- 最后一步就是生成xml,提供了函数直接在根目录下生成atom.xml和rss.xml。当然也可以直接获取内容自己任意加工并重新写入其他目录的文件中
def build_rss_atom(blog_10_items):
fg = FeedGenerator()
fg.id('https://www.chenlongyu.com')
fg.title("Tuesday's Blog")
fg.author({'name': 'Tuesday'})
fg.link(href='https://www.chenlongyu.com/atom.xml', rel='self')
fg.link(href='https://www.chenlongyu.com', rel='alternate')
fg.logo('https://www.chenlongyu.com/static/ico.jpg')
fg.subtitle('喜欢写代码,喜欢研究一切好玩的,喜欢记录,喜欢分享。')
fg.language('zh-CN')
blog_10_items.reverse()
for item in blog_10_items:
fe = fg.add_entry()
fe.title('title')
fe.description('body')
fe.category({"term": 'category'})
fe.id(url)
fe.link(url)
time_temp: datetime.datetime = item[3]['time']
local_dt = time_temp.replace(tzinfo=dateutil.tz.tzutc())
fe.pubDate(local_dt)
# fg.atom_file('atom.xml') # Write the ATOM feed to a file
# fg.rss_file('rss.xml') # Write the RSS feed to a file
atom_feed = fg.atom_str(pretty=True,xml_declaration=False)
atom_feed_str = str(atom_feed, encoding="utf-8")
file_name = r"./path/atom.xml"
with open(file_name, 'w') as f_object:
f_object.write(atom_feed_str)
f_object.close()
rss_feed = fg.rss_str(pretty=True)
rss_feed_str = str(rss_feed, encoding="utf-8")
file_name = r"./path/rss.xml"
with open(file_name, 'w') as f_object:
f_object.write(rss_feed_str)
f_object.close()
有了文件,那后面就自行添加蓝本了,不再赘述。当然,路由可以自己自定义,不过一般来说rss用/feed,atom的用/atom.xml
3. 其他
通过上述方式生成的xml已经转义过了。
如果有需要查询转义符,unicodelookup网站可以很方便地查询,比如输入quotation mark就会看到单双引号的十进制了。
如果傻敷敷地继续用render_template返回直接生成的XML,可能在生产环境你会发现就算更新了博文,rss的xml还是没有更新呢~可能又跑去搜索什么“flask为什么不更新文件”然后得到一堆关于debug_mode的回答。要用send_file,并且把cache_timeout设置短点就OK啦。
0条评论