Feed聚合框架

Django带有一个高聚合的框架让创造RSSAtom更容易。

创建聚合feed,你要做的仅仅是写一个简短的Python类。你想要创造多少,就能创造多少feeds。

Django 也带有一个低等级的生成feed的API。如果你想要生成一个外部的Web内容或者其他普通的方式,你可以使用它。

高等级的框架

概述

高等级的feed聚合框架由Feed类提供。新建一个feed,写一个Feed类,然后指向你的URLconf.

Feed 类

一个 Feed类就是一个提供聚合种子的Python类。一个简单的种子(例如新闻的信息种子,或者只展示博客最新消息)更多功能的种子(例如展示博客中允许展示的特定类别的条目)。

Feed类继承自django.contrib.syndication.views.Feed。它们可以在你代码中的任意一处。

Feed类需要是你URLconf中的实例。

一个简单的示例

这个简单的示例,演示了某站点的最近五条新闻的记录:

  1. from django.contrib.syndication.views import Feed
  2. from django.core.urlresolvers import reverse
  3. from policebeat.models import NewsItem
  4. class LatestEntriesFeed(Feed):
  5. title = "Police beat site news"
  6. link = "/sitenews/"
  7. description = "Updates on changes and additions to police beat central."
  8. def items(self):
  9. return NewsItem.objects.order_by('-pub_date')[:5]
  10. def item_title(self, item):
  11. return item.title
  12. def item_description(self, item):
  13. return item.description
  14. # item_link is only needed if NewsItem has no get_absolute_url method.
  15. def item_link(self, item):
  16. return reverse('news-item', args=[item.pk])

配置一个URL到这个feed,在URLconf中配置一个入口。例如:

  1. from django.conf.urls import url
  2. from myproject.feeds import LatestEntriesFeed
  3. urlpatterns = [
  4. # ...
  5. url(r'^latest/feed/$', LatestEntriesFeed()),
  6. # ...
  7. ]

注意:

  • Feed类继承于django.contrib.syndication.views.Feed.
  • title, linkdescription 分别对应 RSS的 <title>, <link><description> .
  • items()就是一个返回包含feed <item>对象列表的方法.当然,这个例子返回 NewsItem对象是使用 Django的 object-relational mapper, items() 没有返回模型的实例。当然,你可以从Django模型中很容易的获取一些数据,items()可以返回任何你想要的对象。
  • 如果你要创建一个Atom feed,而不是RSS feed,你需要使用subtitle属性替代description。查看Publishing Atom and RSS feeds in tandem里面的例子。

还有一件事没做。在一个 RSS feed中, 每一个 <item> 都有一个<title>, <link><description>. 我们需要告诉框架那些数据放进这些对象中。

  • <title><description>的内容中,Django尝试着在Feed类中召集item_title()item_description()方法。他们会传入一个自己内部的单独的参数 item。这些都是可选的; 默认的是,unicode表示的对象都被使用了

    如果你想要做一些特殊的格式化title或者description,Django templates可以帮助你。他们的路径会被Feed类中的title_templatedescription_template 参数做特殊处理。会通过模板内容的两个变量来返回每一条记录到模板中:

    从下方的 a complex example 使用一个描述的模板。

    Feed.``get_context_data(**kwargs)

    如果您需要提供超过前面提到的两个变量,还有一种方法可以将附加信息传递到标题和描述模板。您可以在Feed子类中提供get_context_data方法的实现。例如:

    1. from mysite.models import Article
    2. from django.contrib.syndication.views import Feed
    3. class ArticlesFeed(Feed):
    4. title = "My articles"
    5. description_template = "feeds/articles.html"
    6. def items(self):
    7. return Article.objects.order_by('-pub_date')[:5]
    8. def get_context_data(self, **kwargs):
    9. context = super(ArticlesFeed, self).get_context_data(**kwargs)
    10. context['foo'] = 'bar'
    11. return context

    和模板:

    1. Something about {{ foo }}: {{ obj.description }}

    此方法将由items()返回的列表中的每个项目调用一次,并使用以下关键字参数:

    • item:当前项目。出于向后兼容性原因,此上下文变量的名称为{% obj %}
    • objget_object()返回的对象。默认情况下,这不会暴露给模板,以避免与{% obj %} ,但您可以在实现get_context_data()时使用它。
    • site:如上所述的当前网站。
    • request:当前请求。

    get_context_data()的行为模仿了generic views的行为 - 你应该调用super()从父类中检索上下文数据,添加您的数据并返回修改后的字典。

  • 要指定<link>的内容,您有两个选项。对于items()中的每个项目,Django首先尝试调用Feed类上的item_link()方法。以类似于标题和描述的方式,它传递单个参数item。如果该方法不存在,Django尝试对该对象执行get_absolute_url()方法。get_absolute_url()item_link()应将项目的网址作为普通的Python字符串返回。与get_absolute_url()一样,item_link()的结果将直接包含在URL中,因此您负责对所有必要的URL进行引用并将其转换为ASCII方法本身。

一个复杂的例子

该框架还通过参数支持更复杂的feed。

例如,网站可以为城市中的每个警察节拍提供最近的犯罪的RSS源。为每个警察节拍创建一个单独的Feed课;这将违反DRY principle并且将数据耦合到编程逻辑。相反,联合框架可让您访问从URLconf传递的参数,以便Feed可以根据Feed的网址中的信息输出项目。

警察打击饲料可以通过这样的URL访问:

  • /beats/613/rss/ - 返回613的最近犯罪。
  • /beats/1424/rss/ - 返回1424年最近的犯罪。

这些可以与URLconf行匹配,例如:

  1. url(r'^beats/(?P<beat_id>[0-9]+)/rss/$', BeatFeed()),

与视图类似,URL中的参数与请求对象一起传递到get_object()方法。

以下是这些特定于节拍的Feed的代码:

  1. from django.contrib.syndication.views import FeedDoesNotExist
  2. from django.shortcuts import get_object_or_404
  3. class BeatFeed(Feed):
  4. description_template = 'feeds/beat_description.html'
  5. def get_object(self, request, beat_id):
  6. return get_object_or_404(Beat, pk=beat_id)
  7. def title(self, obj):
  8. return "Police beat central: Crimes for beat %s" % obj.beat
  9. def link(self, obj):
  10. return obj.get_absolute_url()
  11. def description(self, obj):
  12. return "Crimes recently reported in police beat %s" % obj.beat
  13. def items(self, obj):
  14. return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]

To generate the feed’s &lt;title&gt;, &lt;link&gt; and &lt;description&gt;, Django uses the title(), link() and description() methods. 在前面的示例中,它们是简单的字符串类属性,但是本示例说明它们可以是字符串方法。对于titlelinkdescription中的每一个,Django都遵循此算法:

  • 首先,它尝试调用传递obj参数的方法,其中obj是由get_object()返回的对象。
  • 如果没有,它试图调用没有参数的方法。
  • 如果没有,它使用类属性。

还要注意,items()也遵循相同的算法 - 首先,它尝试items(obj),然后items() items类属性(它应该是一个列表)。

我们正在使用模板作为项目描述。它可以很简单:

  1. {{ obj.description }}

但是,您可以根据需要自由添加格式。

下面的ExampleFeed类提供了有关Feed类的方法和属性的完整文档。

指定Feed的类型

默认情况下,此框架中生成的Feed使用RSS 2.0。

要更改此属性,请向您的Feed类添加feed_type属性,如下所示:

  1. from django.utils.feedgenerator import Atom1Feed
  2. class MyFeed(Feed):
  3. feed_type = Atom1Feed

请注意,您将feed_type设置为类对象,而不是实例。

目前可用的Feed类型有:

附件

要指定机柜(例如用于创建Podcast Feed的机柜),请使用item_enclosure_urlitem_enclosure_lengthitem_enclosure_mime_type挂钩。有关用法示例,请参见下面的ExampleFeed类。

语言

由联合框架创建的Feed会自动包含适当的&lt;language&gt;标记(RSS 2.0)或xml:lang属性(Atom)。这直接来自您的LANGUAGE_CODE设置。

网址

link方法/属性可以返回绝对路径(例如"/blog/")或具有完全限定域和协议的URL(例如"http://www.example.com/blog/")。如果link未返回域,则整合框架将根据您的SITE_ID setting

Atom Feed需要定义Feed的当前位置的&lt; link rel =“self”&gt;

串联发布Atom和RSS Feed

有些开发人员喜欢提供Atom RSS版本的Feed。使用Django很容易:只需创建Feed类的子类,并将feed_type设置为不同的类型即可。然后更新您的URLconf以添加额外的版本。

这里有一个完整的例子:

  1. from django.contrib.syndication.views import Feed
  2. from policebeat.models import NewsItem
  3. from django.utils.feedgenerator import Atom1Feed
  4. class RssSiteNewsFeed(Feed):
  5. title = "Police beat site news"
  6. link = "/sitenews/"
  7. description = "Updates on changes and additions to police beat central."
  8. def items(self):
  9. return NewsItem.objects.order_by('-pub_date')[:5]
  10. class AtomSiteNewsFeed(RssSiteNewsFeed):
  11. feed_type = Atom1Feed
  12. subtitle = RssSiteNewsFeed.description

注意

在此示例中,RSS提要使用description,而Atom提要使用subtitle。这是因为Atom Feed不提供Feed级“说明”,但他们提供“字幕”。

如果您在Feed类中提供description,Django将不会自动将其放入subtitle字幕和描述不一定是同一件事。而应定义subtitle属性。

在上面的示例中,我们只需将Atom Feed的subtitle设置为RSS Feed的description,因为它已经很短。

和附带的URLconf:

  1. from django.conf.urls import url
  2. from myproject.feeds import RssSiteNewsFeed, AtomSiteNewsFeed
  3. urlpatterns = [
  4. # ...
  5. url(r'^sitenews/rss/$', RssSiteNewsFeed()),
  6. url(r'^sitenews/atom/$', AtomSiteNewsFeed()),
  7. # ...
  8. ]

Feed类引用

class views.``Feed

此示例说明Feed类的所有可能的属性和方法:

  1. from django.contrib.syndication.views import Feed
  2. from django.utils import feedgenerator
  3. class ExampleFeed(Feed):
  4. # FEED TYPE -- Optional. This should be a class that subclasses
  5. # django.utils.feedgenerator.SyndicationFeed. This designates
  6. # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If
  7. # you don't specify feed_type, your feed will be RSS 2.0\. This
  8. # should be a class, not an instance of the class.
  9. feed_type = feedgenerator.Rss201rev2Feed
  10. # TEMPLATE NAMES -- Optional. These should be strings
  11. # representing names of Django templates that the system should
  12. # use in rendering the title and description of your feed items.
  13. # Both are optional. If a template is not specified, the
  14. # item_title() or item_description() methods are used instead.
  15. title_template = None
  16. description_template = None
  17. # TITLE -- One of the following three is required. The framework
  18. # looks for them in this order.
  19. def title(self, obj):
  20. """
  21. Takes the object returned by get_object() and returns the
  22. feed's title as a normal Python string.
  23. """
  24. def title(self):
  25. """
  26. Returns the feed's title as a normal Python string.
  27. """
  28. title = 'foo' # Hard-coded title.
  29. # LINK -- One of the following three is required. The framework
  30. # looks for them in this order.
  31. def link(self, obj):
  32. """
  33. # Takes the object returned by get_object() and returns the URL
  34. # of the HTML version of the feed as a normal Python string.
  35. """
  36. def link(self):
  37. """
  38. Returns the URL of the HTML version of the feed as a normal Python
  39. string.
  40. """
  41. link = '/blog/' # Hard-coded URL.
  42. # FEED_URL -- One of the following three is optional. The framework
  43. # looks for them in this order.
  44. def feed_url(self, obj):
  45. """
  46. # Takes the object returned by get_object() and returns the feed's
  47. # own URL as a normal Python string.
  48. """
  49. def feed_url(self):
  50. """
  51. Returns the feed's own URL as a normal Python string.
  52. """
  53. feed_url = '/blog/rss/' # Hard-coded URL.
  54. # GUID -- One of the following three is optional. The framework looks
  55. # for them in this order. This property is only used for Atom feeds
  56. # (where it is the feed-level ID element). If not provided, the feed
  57. # link is used as the ID.
  58. def feed_guid(self, obj):
  59. """
  60. Takes the object returned by get_object() and returns the globally
  61. unique ID for the feed as a normal Python string.
  62. """
  63. def feed_guid(self):
  64. """
  65. Returns the feed's globally unique ID as a normal Python string.
  66. """
  67. feed_guid = '/foo/bar/1234' # Hard-coded guid.
  68. # DESCRIPTION -- One of the following three is required. The framework
  69. # looks for them in this order.
  70. def description(self, obj):
  71. """
  72. Takes the object returned by get_object() and returns the feed's
  73. description as a normal Python string.
  74. """
  75. def description(self):
  76. """
  77. Returns the feed's description as a normal Python string.
  78. """
  79. description = 'Foo bar baz.' # Hard-coded description.
  80. # AUTHOR NAME --One of the following three is optional. The framework
  81. # looks for them in this order.
  82. def author_name(self, obj):
  83. """
  84. Takes the object returned by get_object() and returns the feed's
  85. author's name as a normal Python string.
  86. """
  87. def author_name(self):
  88. """
  89. Returns the feed's author's name as a normal Python string.
  90. """
  91. author_name = 'Sally Smith' # Hard-coded author name.
  92. # AUTHOR EMAIL --One of the following three is optional. The framework
  93. # looks for them in this order.
  94. def author_email(self, obj):
  95. """
  96. Takes the object returned by get_object() and returns the feed's
  97. author's email as a normal Python string.
  98. """
  99. def author_email(self):
  100. """
  101. Returns the feed's author's email as a normal Python string.
  102. """
  103. author_email = 'test@example.com' # Hard-coded author email.
  104. # AUTHOR LINK --One of the following three is optional. The framework
  105. # looks for them in this order. In each case, the URL should include
  106. # the "http://" and domain name.
  107. def author_link(self, obj):
  108. """
  109. Takes the object returned by get_object() and returns the feed's
  110. author's URL as a normal Python string.
  111. """
  112. def author_link(self):
  113. """
  114. Returns the feed's author's URL as a normal Python string.
  115. """
  116. author_link = 'http://www.example.com/' # Hard-coded author URL.
  117. # CATEGORIES -- One of the following three is optional. The framework
  118. # looks for them in this order. In each case, the method/attribute
  119. # should return an iterable object that returns strings.
  120. def categories(self, obj):
  121. """
  122. Takes the object returned by get_object() and returns the feed's
  123. categories as iterable over strings.
  124. """
  125. def categories(self):
  126. """
  127. Returns the feed's categories as iterable over strings.
  128. """
  129. categories = ("python", "django") # Hard-coded list of categories.
  130. # COPYRIGHT NOTICE -- One of the following three is optional. The
  131. # framework looks for them in this order.
  132. def feed_copyright(self, obj):
  133. """
  134. Takes the object returned by get_object() and returns the feed's
  135. copyright notice as a normal Python string.
  136. """
  137. def feed_copyright(self):
  138. """
  139. Returns the feed's copyright notice as a normal Python string.
  140. """
  141. feed_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
  142. # TTL -- One of the following three is optional. The framework looks
  143. # for them in this order. Ignored for Atom feeds.
  144. def ttl(self, obj):
  145. """
  146. Takes the object returned by get_object() and returns the feed's
  147. TTL (Time To Live) as a normal Python string.
  148. """
  149. def ttl(self):
  150. """
  151. Returns the feed's TTL as a normal Python string.
  152. """
  153. ttl = 600 # Hard-coded Time To Live.
  154. # ITEMS -- One of the following three is required. The framework looks
  155. # for them in this order.
  156. def items(self, obj):
  157. """
  158. Takes the object returned by get_object() and returns a list of
  159. items to publish in this feed.
  160. """
  161. def items(self):
  162. """
  163. Returns a list of items to publish in this feed.
  164. """
  165. items = ('Item 1', 'Item 2') # Hard-coded items.
  166. # GET_OBJECT -- This is required for feeds that publish different data
  167. # for different URL parameters. (See "A complex example" above.)
  168. def get_object(self, request, *args, **kwargs):
  169. """
  170. Takes the current request and the arguments from the URL, and
  171. returns an object represented by this feed. Raises
  172. django.core.exceptions.ObjectDoesNotExist on error.
  173. """
  174. # ITEM TITLE AND DESCRIPTION -- If title_template or
  175. # description_template are not defined, these are used instead. Both are
  176. # optional, by default they will use the unicode representation of the
  177. # item.
  178. def item_title(self, item):
  179. """
  180. Takes an item, as returned by items(), and returns the item's
  181. title as a normal Python string.
  182. """
  183. def item_title(self):
  184. """
  185. Returns the title for every item in the feed.
  186. """
  187. item_title = 'Breaking News: Nothing Happening' # Hard-coded title.
  188. def item_description(self, item):
  189. """
  190. Takes an item, as returned by items(), and returns the item's
  191. description as a normal Python string.
  192. """
  193. def item_description(self):
  194. """
  195. Returns the description for every item in the feed.
  196. """
  197. item_description = 'A description of the item.' # Hard-coded description.
  198. def get_context_data(self, **kwargs):
  199. """
  200. Returns a dictionary to use as extra context if either
  201. description_template or item_template are used.
  202. Default implementation preserves the old behavior
  203. of using {'obj': item, 'site': current_site} as the context.
  204. """
  205. # ITEM LINK -- One of these three is required. The framework looks for
  206. # them in this order.
  207. # First, the framework tries the two methods below, in
  208. # order. Failing that, it falls back to the get_absolute_url()
  209. # method on each item returned by items().
  210. def item_link(self, item):
  211. """
  212. Takes an item, as returned by items(), and returns the item's URL.
  213. """
  214. def item_link(self):
  215. """
  216. Returns the URL for every item in the feed.
  217. """
  218. # ITEM_GUID -- The following method is optional. If not provided, the
  219. # item's link is used by default.
  220. def item_guid(self, obj):
  221. """
  222. Takes an item, as return by items(), and returns the item's ID.
  223. """
  224. # ITEM_GUID_IS_PERMALINK -- The following method is optional. If
  225. # provided, it sets the 'isPermaLink' attribute of an item's
  226. # GUID element. This method is used only when 'item_guid' is
  227. # specified.
  228. def item_guid_is_permalink(self, obj):
  229. """
  230. Takes an item, as returned by items(), and returns a boolean.
  231. """
  232. item_guid_is_permalink = False # Hard coded value
  233. # ITEM AUTHOR NAME -- One of the following three is optional. The
  234. # framework looks for them in this order.
  235. def item_author_name(self, item):
  236. """
  237. Takes an item, as returned by items(), and returns the item's
  238. author's name as a normal Python string.
  239. """
  240. def item_author_name(self):
  241. """
  242. Returns the author name for every item in the feed.
  243. """
  244. item_author_name = 'Sally Smith' # Hard-coded author name.
  245. # ITEM AUTHOR EMAIL --One of the following three is optional. The
  246. # framework looks for them in this order.
  247. #
  248. # If you specify this, you must specify item_author_name.
  249. def item_author_email(self, obj):
  250. """
  251. Takes an item, as returned by items(), and returns the item's
  252. author's email as a normal Python string.
  253. """
  254. def item_author_email(self):
  255. """
  256. Returns the author email for every item in the feed.
  257. """
  258. item_author_email = 'test@example.com' # Hard-coded author email.
  259. # ITEM AUTHOR LINK -- One of the following three is optional. The
  260. # framework looks for them in this order. In each case, the URL should
  261. # include the "http://" and domain name.
  262. #
  263. # If you specify this, you must specify item_author_name.
  264. def item_author_link(self, obj):
  265. """
  266. Takes an item, as returned by items(), and returns the item's
  267. author's URL as a normal Python string.
  268. """
  269. def item_author_link(self):
  270. """
  271. Returns the author URL for every item in the feed.
  272. """
  273. item_author_link = 'http://www.example.com/' # Hard-coded author URL.
  274. # ITEM ENCLOSURE URL -- One of these three is required if you're
  275. # publishing enclosures. The framework looks for them in this order.
  276. def item_enclosure_url(self, item):
  277. """
  278. Takes an item, as returned by items(), and returns the item's
  279. enclosure URL.
  280. """
  281. def item_enclosure_url(self):
  282. """
  283. Returns the enclosure URL for every item in the feed.
  284. """
  285. item_enclosure_url = "/foo/bar.mp3" # Hard-coded enclosure link.
  286. # ITEM ENCLOSURE LENGTH -- One of these three is required if you're
  287. # publishing enclosures. The framework looks for them in this order.
  288. # In each case, the returned value should be either an integer, or a
  289. # string representation of the integer, in bytes.
  290. def item_enclosure_length(self, item):
  291. """
  292. Takes an item, as returned by items(), and returns the item's
  293. enclosure length.
  294. """
  295. def item_enclosure_length(self):
  296. """
  297. Returns the enclosure length for every item in the feed.
  298. """
  299. item_enclosure_length = 32000 # Hard-coded enclosure length.
  300. # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're
  301. # publishing enclosures. The framework looks for them in this order.
  302. def item_enclosure_mime_type(self, item):
  303. """
  304. Takes an item, as returned by items(), and returns the item's
  305. enclosure MIME type.
  306. """
  307. def item_enclosure_mime_type(self):
  308. """
  309. Returns the enclosure MIME type for every item in the feed.
  310. """
  311. item_enclosure_mime_type = "audio/mpeg" # Hard-coded enclosure MIME type.
  312. # ITEM PUBDATE -- It's optional to use one of these three. This is a
  313. # hook that specifies how to get the pubdate for a given item.
  314. # In each case, the method/attribute should return a Python
  315. # datetime.datetime object.
  316. def item_pubdate(self, item):
  317. """
  318. Takes an item, as returned by items(), and returns the item's
  319. pubdate.
  320. """
  321. def item_pubdate(self):
  322. """
  323. Returns the pubdate for every item in the feed.
  324. """
  325. item_pubdate = datetime.datetime(2005, 5, 3) # Hard-coded pubdate.
  326. # ITEM UPDATED -- It's optional to use one of these three. This is a
  327. # hook that specifies how to get the updateddate for a given item.
  328. # In each case, the method/attribute should return a Python
  329. # datetime.datetime object.
  330. def item_updateddate(self, item):
  331. """
  332. Takes an item, as returned by items(), and returns the item's
  333. updateddate.
  334. """
  335. def item_updateddate(self):
  336. """
  337. Returns the updateddated for every item in the feed.
  338. """
  339. item_updateddate = datetime.datetime(2005, 5, 3) # Hard-coded updateddate.
  340. # ITEM CATEGORIES -- It's optional to use one of these three. This is
  341. # a hook that specifies how to get the list of categories for a given
  342. # item. In each case, the method/attribute should return an iterable
  343. # object that returns strings.
  344. def item_categories(self, item):
  345. """
  346. Takes an item, as returned by items(), and returns the item's
  347. categories.
  348. """
  349. def item_categories(self):
  350. """
  351. Returns the categories for every item in the feed.
  352. """
  353. item_categories = ("python", "django") # Hard-coded categories.
  354. # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
  355. # following three is optional. The framework looks for them in this
  356. # order.
  357. def item_copyright(self, obj):
  358. """
  359. Takes an item, as returned by items(), and returns the item's
  360. copyright notice as a normal Python string.
  361. """
  362. def item_copyright(self):
  363. """
  364. Returns the copyright notice for every item in the feed.
  365. """
  366. item_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.

低级框架

在后台,高级RSS框架使用较低级别的框架来生成订阅源的XML。此框架存在于单个模块中:django / utils / feedgenerator.py

您自己使用此框架,用于生成较低级别的Feed。您还可以创建自定义Feed生成器子类,以与feed_type Feed选项一起使用。

联合供稿 classes

feedgenerator模块包含基类:

和几个子类:

这三个类中的每一个都知道如何将某种类型的feed呈现为XML。他们共享这个接口:

SyndicationFeed.__init__()

使用给定的元数据字典初始化Feed,该元数据字典应用于整个Feed。必需的关键字参数为:

  • title
  • link
  • description

还有一堆其他可选关键字:

  • language
  • author_email
  • author_name
  • author_link
  • subtitle
  • categories
  • feed_url
  • feed_copyright
  • feed_guid
  • ttl

您传递给__init__的任何其他关键字参数将存储在self.feed中以与自定义Feed生成器配合使用。

所有参数都应该是Unicode对象,除了categories,它应该是Unicode对象序列。

SyndicationFeed.add_item()

向具有给定参数的Feed中添加项目。

必需的关键字参数为:

  • title
  • link
  • description

可选的关键字参数为:

  • author_email
  • author_name
  • author_link
  • pubdate
  • comments
  • unique_id
  • enclosure
  • categories
  • item_copyright
  • ttl
  • updateddate

将为自定义Feed生成器存储额外的关键字参数。

所有参数,如果给定,应该是Unicode对象,除了:

New in Django 1.7:

已添加可选的updateddate参数。

SyndicationFeed.write()

Outputs the feed in the given encoding to outfile, which is a file-like object.

SyndicationFeed.writeString()

Returns the feed as a string in the given encoding.

例如,要创建Atom 1.0订阅源并将其打印到标准输出:

  1. >>> from django.utils import feedgenerator
  2. >>> from datetime import datetime
  3. >>> f = feedgenerator.Atom1Feed(
  4. ... title="My Weblog",
  5. ... link="http://www.example.com/",
  6. ... description="In which I write about what I ate today.",
  7. ... language="en",
  8. ... author_name="Myself",
  9. ... feed_url="http://example.com/atom.xml")
  10. >>> f.add_item(title="Hot dog today",
  11. ... link="http://www.example.com/entries/1/",
  12. ... pubdate=datetime.now(),
  13. ... description="<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>")
  14. >>> print(f.writeString('UTF-8'))
  15. <?xml version="1.0" encoding="UTF-8"?>
  16. <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  17. ...
  18. </feed>

自定义Feed生成器

如果您需要生成自定义Feed格式,您有几个选项。

如果Feed格式是完全自定义的,您需要将SyndicationFeed作为子类,并完全替换write()writeString()方法。

但是,如果Feed格式是RSS或Atom分拆(即GeoRSS,Apple的iTunes podcast格式等),则您有了更好的选择。这些类型的Feed通常会向底层格式添加额外的元素和/或属性,并且有一组方法可以SyndicationFeed调用以获取这些额外的属性。因此,您可以对相应的Feed生成器类(Atom1FeedRss201rev2Feed)进行子类化,并扩展这些回调。他们是:

SyndicationFeed.root_attributes(self, )

Return a dict of attributes to add to the root feed element (feed/channel).

SyndicationFeed.add_root_elements(self, handler)

Callback to add elements inside the root feed element (feed/channel). handler is an XMLGenerator from Python’s built-in SAX library; you’ll call methods on it to add to the XML document in process.

SyndicationFeed.item_attributes(self, item)

Return a dict of attributes to add to each item (item/entry) element. The argument, item, is a dictionary of all the data passed to SyndicationFeed.add_item().

SyndicationFeed.add_item_elements(self, handler, item)

Callback to add elements to each item (item/entry) element. handler and item are as above.

警告

如果您覆盖任何这些方法,请务必调用超类方法,因为它们为每种Feed格式添加了必需的元素。

例如,您可能开始实现iTunes RSS Feed生成器,如:

  1. class iTunesFeed(Rss201rev2Feed):
  2. def root_attributes(self):
  3. attrs = super(iTunesFeed, self).root_attributes()
  4. attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
  5. return attrs
  6. def add_root_elements(self, handler):
  7. super(iTunesFeed, self).add_root_elements(handler)
  8. handler.addQuickElement('itunes:explicit', 'clean')

显然,对于一个完整的自定义feed类,还有很多工作要做,但上面的例子应该展示基本的想法。

{% endraw %}