给python的django框架下搭建的blog添加rss功能的教程

前些天有位网友建议我在博客中添加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()),
)

Posted in 未分类

发表评论