Django RSS

Django带有聚合feed生成框架。有了它,你可以创建RSS或Atom只需继承django.contrib.syndication.views.Feed类。

让我们创建一个订阅源的应用程序。

#Filename:example.py#Copyright:2020ByNhooo#Authorby:www.shangmayuan.com#Date:2020-08-08fromdjango.contrib.syndication.viewsimportFeedfromdjango.contrib.commentsimportCommentfromdjango.core.urlresolversimportreverseclassDreamrealCommentsFeed(Feed):title="Dreamreal'scomments"link="/drcomments/"description="UpdatesonnewcommentsonDreamrealentry."defitems(self):returnComment.objects.all().order_by("-submit_date")[:5]defitem_title(self,item):returnitem.user_namedefitem_description(self,item):returnitem.commentdefitem_link(self,item):returnreverse('comment',kwargs={'object_pk':item.pk})

在feed类,title,link和description属性对应标准RSS的<title>,<link>和<description>元素。

条目方法返回应该进入feed的item的元素。在我们的示例中是最后五个注释。

现在,我们有feed,并添加评论在视图views.py,以显示我们的评论−

#Filename:example.py#Copyright:2020ByNhooo#Authorby:www.shangmayuan.com#Date:2020-08-08fromdjango.contrib.commentsimportCommentdefcomment(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>returnHttpResponse(text)

我们还需要一些网址在myappurls.py中映射−

#Filename:example.py#Copyright:2020ByNhooo#Authorby:www.shangmayuan.com#Date:2020-08-08frommyapp.feedsimportDreamrealCommentsFeedfromdjango.conf.urlsimportpatterns,urlurlpatterns+=patterns('',url(r'^latest/comments/',DreamrealCommentsFeed()),url(r'^comment/(?P\w+)/','comment',name='comment'),)

当访问/myapp/latest/comments/会得到 feed− feed

当点击其中的一个用户名都会得到:/myapp/comment/comment_id在您的评论视图定义之前,会得到− feed

因此,定义一个RSS源是Feed类的子类,并确保这些URL(一个用于访问feed,一个用于访问feed元素)的定义。正如评论,这可以连接到您的应用程序的任何模型。

编辑于2024-05-20 20:23