給Python的Django架構下搭建的BLOG添加RSS功能的教程

來源:互聯網
上載者:User
前些天有位網友建議我在部落格中添加RSS訂閱功能,覺得挺好,所以自己抽空看了一下如何在Django中添加RSS功能,發現使用Django中的syndication feed framework很容易實現。

具體實現步驟和代碼如下:

1、Feed類

# -*- coding: utf-8 -*-from django.conf import settingsfrom django.contrib.syndication.views import Feedfrom django.utils.feedgenerator import Rss201rev2Feed from blog.models import Articlefrom .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, urlelse: from django.conf.urls.defaults import patterns, include, urlfrom .feeds import LatestArticleFeed  urlpatterns = patterns( '', url(r'^feed/$', LatestArticleFeed()),)
  • 相關文章

    聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.