给Python的Django框架下搭建的BLOG添加RSS功能的教程

yipeiwu_com5年前Python基础

前些天有位网友建议我在博客中添加RSS订阅功能,觉得挺好,所以自己抽空看了一下如何在Django中添加RSS功能,发现使用Django中的syndication feed framework很容易实现。

    具体实现步骤和代码如下:

    1、Feed类

# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.syndication.views import Feed
from django.utils.feedgenerator import Rss201rev2Feed
 
from blog.models import Article
from .constants import SYNC_STATUS
 
 
class ExtendedRSSFeed(Rss201rev2Feed):
 mime_type = 'application/xml'
 """
 Create a type of RSS feed that has content:encoded elements.
 """
 def root_attributes(self):
  attrs = super(ExtendedRSSFeed, self).root_attributes()
  attrs['xmlns:content'] = 'http://purl.org/rss/1.0/modules/content/'
  return attrs
 
 def add_item_elements(self, handler, item):
  super(ExtendedRSSFeed, self).add_item_elements(handler, item)
  handler.addQuickElement(u'content:encoded', item['content_encoded'])
 
 
class LatestArticleFeed(Feed):
 feed_type = ExtendedRSSFeed
 
 title = settings.WEBSITE_NAME
 link = settings.WEBSITE_URL
 author = settings.WEBSITE_NAME
 description = settings.WEBSITE_DESC + u"关注python、django、vim、linux、web开发和互联网"
 
 def items(self):
  return Article.objects.filter(hided=False, published=True, sync_status=SYNC_STATUS.SYNCED).order_by('-publish_date')[:10]
 
 def item_extra_kwargs(self, item):
  return {'content_encoded': self.item_content_encoded(item)}
 
 def item_title(self, item):
  return item.title
 
 # item_link is only needed if NewsItem has no get_absolute_url method.
 def item_link(self, item):
  return '/article/%s/' % item.slug
 
 def item_description(self, item):
  return item.description
 
 def item_author_name(self, item):
  return item.creator.get_full_name()
 
 def item_pubdate(self, item):
  return item.publish_date
 
 def item_content_encoded(self, item):
  return item.content

    2、URL配置

from django import VERSION
 
if VERSION[0: 2] > (1, 3):
 from django.conf.urls import patterns, include, url
else:
 from django.conf.urls.defaults import patterns, include, url
from .feeds import LatestArticleFeed
 
 
urlpatterns = patterns(
 '',
 url(r'^feed/$', LatestArticleFeed()),
)

相关文章

pandas 根据列的值选取所有行的示例

如下所示: # 选取等于某些值的行记录 用 == df.loc[df['column_name'] == some_value] # 选取某列是否是某一类型的数值 用 isin...

Python实现国外赌场热门游戏Craps(双骰子)

运行方法:     1. 打开python2 IDLE;     2. 输入 from craps import * &nb...

Python微信库:itchat的用法详解

Python微信库:itchat的用法详解

在论坛上看到了用Python登录微信并实现自动签到,才了解到一个新的Python库: itchat 库文档说明链接在这:  itchat 我存个档在我网站(主要是我打...

Python功能点实现:函数级/代码块级计时器

工程中我们常常需要对某一个函数或者一块代码计时,从而监测系统关键位置的性能。计时方法是在代码块前后分别记录当前系统时间,然后两者相减得到代码块的耗时。最简单原始的实现类似: from...

Python基于递归和非递归算法求两个数最大公约数、最小公倍数示例

本文实例讲述了Python基于递归和非递归算法求两个数最大公约数、最小公倍数。分享给大家供大家参考,具体如下: 最大公约数和最小公倍数的概念大家都很熟悉了,在这里就不多说了,今天这个是因...