给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()),
)

相关文章

使用python实现滑动验证码功能

使用python实现滑动验证码功能

首先安装一个需要用到的模块 pip install social-auth-app-django 安装完后在终端输入pip list会看到 social-auth-app-djang...

Django如何使用第三方服务发送电子邮件

Django如何使用第三方服务发送电子邮件

在 Django 网站中使用 mailgun 的邮件收发服务。 1.在 mailgun 官网上注册个账号(免费,免费账号每个月有10000条收发邮件的服务,对我来说已经完全够用了),注册...

tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用

tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用

1.创建tfrecord tfrecord支持写入三种格式的数据:string,int64,float32,以列表的形式分别通过tf.train.BytesList、tf.train.I...

自定义django admin model表单提交的例子

自定义django admin model表单提交的例子

如下所示: 希望可以从对admin提交的密码加密,并验证电话号码均为数字。 查看admin.py from django.contrib import admin class co...

在python中使用正则表达式查找可嵌套字符串组

在网上看到一个小需求,需要用正则表达式来处理。原需求如下: 找出文本中包含”因为……所以”的句子,并以两个词为中心对齐输出前后3个字,中间全输出,如果“因为”和“所以”中间还存在“因为”...