Django - RSS



Django 自帶一個 syndication feed 生成框架。透過它,你只需繼承django.contrib.syndication.views.Feed 類就可以建立 RSS 或 Atom feeds。

讓我們為應用中最新的評論建立一個 feed(另見 Django - 評論框架章節)。為此,讓我們建立一個 myapp/feeds.py 並定義我們的 feed(你可以將 feeds 類放在程式碼結構中的任何位置)。

from django.contrib.syndication.views import Feed
from django.contrib.comments import Comment
from django.core.urlresolvers import reverse

class DreamrealCommentsFeed(Feed):
   title = "Dreamreal's comments"
   link = "/drcomments/"
   description = "Updates on new comments on Dreamreal entry."

   def items(self):
      return Comment.objects.all().order_by("-submit_date")[:5]
		
   def item_title(self, item):
      return item.user_name
		
   def item_description(self, item):
      return item.comment
		
   def item_link(self, item):
      return reverse('comment', kwargs = {'object_pk':item.pk})
  • 在我們的 feed 類中,titlelinkdescription 屬性對應於標準 RSS 的<title><link><description> 元素。

  • items 方法返回應該作為 item 元素新增到 feed 中的元素。在本例中是最近五條評論。

  • item_title 方法將獲取作為 feed 專案標題的內容。在本例中,標題將是使用者名稱。

  • item_description 方法將獲取作為 feed 專案描述的內容。在本例中是評論本身。

  • item_link 方法將構建指向完整專案的連結。在本例中,它將引導你到評論。

現在我們有了 feed,讓我們在 views.py 中新增一個評論檢視來顯示我們的評論:

from django.contrib.comments import Comment

def comment(request, object_pk):
   mycomment = Comment.objects.get(object_pk = object_pk)
   text = '<strong>User :</strong> %s <p>'%mycomment.user_name</p>
   text += '<strong>Comment :</strong> %s <p>'%mycomment.comment</p>
   return HttpResponse(text)

我們還需要在 myapp 的 urls.py 中新增一些 URL 進行對映:

from myapp.feeds import DreamrealCommentsFeed
from django.conf.urls import patterns, url

urlpatterns += patterns('',
   url(r'^latest/comments/', DreamrealCommentsFeed()),
   url(r'^comment/(?P\w+)/', 'comment', name = 'comment'),
)

訪問 /myapp/latest/comments/ 將獲得我們的 feed:

Django RSS Example

然後點選使用者名稱之一將跳轉到:/myapp/comment/comment_id(如我們之前的評論檢視中定義的那樣),你將獲得:

Django RSS Redirected Page

因此,定義 RSS feed 只需要繼承 Feed 類並確保定義了 URL(一個用於訪問 feed,一個用於訪問 feed 元素)。與評論一樣,這可以附加到應用中的任何模型。

廣告