Django RSS

Django帶有聚合feed生成框架。有了它,你可以創建RSS或Atom只需繼承django.contrib.syndication.views.Feed類。

讓我們創建一個訂閱源的應用程式。

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類, title, link 和 description 屬性對應標準RSS 的<title>, <link> 和 <description>元素。

  • 條目方法返回應該進入feed的item的元素。在我們的示例中是最後五個注釋。

現在,我們有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中映射 −

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 −

當點擊其中的一個用戶名都會得到:/myapp/comment/comment_id 在您的評論視圖定義之前,會得到 −

因此,定義一個RSS源是 Feed 類的子類,並確保這些URL(一個用於訪問feed,一個用於訪問feed元素)的定義。 正如評論,這可以連接到您的應用程式的任何模型。



上一篇: Django緩存 下一篇: Django Ajax應用