syndication.txt 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. ==============================
  2. The syndication feed framework
  3. ==============================
  4. .. module:: django.contrib.syndication
  5. :synopsis: A framework for generating syndication feeds, in RSS and Atom,
  6. quite easily.
  7. Django comes with a high-level syndication-feed-generating framework
  8. that makes creating RSS_ and Atom_ feeds easy.
  9. To create any syndication feed, all you have to do is write a short
  10. Python class. You can create as many feeds as you want.
  11. Django also comes with a lower-level feed-generating API. Use this if
  12. you want to generate feeds outside of a Web context, or in some other
  13. lower-level way.
  14. .. _RSS: http://www.whatisrss.com/
  15. .. _Atom: http://www.atomenabled.org/
  16. The high-level framework
  17. ========================
  18. .. versionchanged:: 1.2
  19. The high-level feeds framework was refactored in Django 1.2. The
  20. pre-1.2 interface has been removed in Django 1.4.
  21. Overview
  22. --------
  23. The high-level feed-generating framework is supplied by the
  24. :class:`~django.contrib.syndication.views.Feed` class. To create a
  25. feed, write a :class:`~django.contrib.syndication.views.Feed` class
  26. and point to an instance of it in your :doc:`URLconf
  27. </topics/http/urls>`.
  28. Feed classes
  29. ------------
  30. A :class:`~django.contrib.syndication.views.Feed` class is a Python
  31. class that represents a syndication feed. A feed can be simple (e.g.,
  32. a "site news" feed, or a basic feed displaying the latest entries of a
  33. blog) or more complex (e.g., a feed displaying all the blog entries in
  34. a particular category, where the category is variable).
  35. Feed classes subclass :class:`django.contrib.syndication.views.Feed`.
  36. They can live anywhere in your codebase.
  37. Instances of :class:`~django.contrib.syndication.views.Feed` classes
  38. are views which can be used in your :doc:`URLconf </topics/http/urls>`.
  39. A simple example
  40. ----------------
  41. This simple example, taken from `chicagocrime.org`_, describes a feed of the
  42. latest five news items::
  43. from django.contrib.syndication.views import Feed
  44. from chicagocrime.models import NewsItem
  45. class LatestEntriesFeed(Feed):
  46. title = "Chicagocrime.org site news"
  47. link = "/sitenews/"
  48. description = "Updates on changes and additions to chicagocrime.org."
  49. def items(self):
  50. return NewsItem.objects.order_by('-pub_date')[:5]
  51. def item_title(self, item):
  52. return item.title
  53. def item_description(self, item):
  54. return item.description
  55. To connect a URL to this feed, put an instance of the Feed object in
  56. your :doc:`URLconf </topics/http/urls>`. For example::
  57. from django.conf.urls import patterns, url, include
  58. from myproject.feeds import LatestEntriesFeed
  59. urlpatterns = patterns('',
  60. # ...
  61. (r'^latest/feed/$', LatestEntriesFeed()),
  62. # ...
  63. )
  64. Note:
  65. * The Feed class subclasses :class:`django.contrib.syndication.views.Feed`.
  66. * ``title``, ``link`` and ``description`` correspond to the
  67. standard RSS ``<title>``, ``<link>`` and ``<description>`` elements,
  68. respectively.
  69. * ``items()`` is, simply, a method that returns a list of objects that
  70. should be included in the feed as ``<item>`` elements. Although this
  71. example returns ``NewsItem`` objects using Django's
  72. :doc:`object-relational mapper </ref/models/querysets>`, ``items()``
  73. doesn't have to return model instances. Although you get a few bits of
  74. functionality "for free" by using Django models, ``items()`` can
  75. return any type of object you want.
  76. * If you're creating an Atom feed, rather than an RSS feed, set the
  77. ``subtitle`` attribute instead of the ``description`` attribute.
  78. See `Publishing Atom and RSS feeds in tandem`_, later, for an example.
  79. One thing is left to do. In an RSS feed, each ``<item>`` has a ``<title>``,
  80. ``<link>`` and ``<description>``. We need to tell the framework what data to put
  81. into those elements.
  82. * For the contents of ``<title>`` and ``<description>``, Django tries
  83. calling the methods ``item_title()`` and ``item_description()`` on
  84. the :class:`~django.contrib.syndication.views.Feed` class. They are passed
  85. a single parameter, ``item``, which is the object itself. These are
  86. optional; by default, the unicode representation of the object is used for
  87. both.
  88. If you want to do any special formatting for either the title or
  89. description, :doc:`Django templates </topics/templates>` can be used
  90. instead. Their paths can be specified with the ``title_template`` and
  91. ``description_template`` attributes on the
  92. :class:`~django.contrib.syndication.views.Feed` class. The templates are
  93. rendered for each item and are passed two template context variables:
  94. * ``{{ obj }}`` -- The current object (one of whichever objects you
  95. returned in ``items()``).
  96. * ``{{ site }}`` -- A :class:`django.contrib.sites.models.Site` object
  97. representing the current site. This is useful for ``{{ site.domain
  98. }}`` or ``{{ site.name }}``. If you do *not* have the Django sites
  99. framework installed, this will be set to a
  100. :class:`django.contrib.sites.models.RequestSite` object. See the
  101. :ref:`RequestSite section of the sites framework documentation
  102. <requestsite-objects>` for more.
  103. See `a complex example`_ below that uses a description template.
  104. * To specify the contents of ``<link>``, you have two options. For each item
  105. in ``items()``, Django first tries calling the
  106. ``item_link()`` method on the
  107. :class:`~django.contrib.syndication.views.Feed` class. In a similar way to
  108. the title and description, it is passed it a single parameter,
  109. ``item``. If that method doesn't exist, Django tries executing a
  110. ``get_absolute_url()`` method on that object. Both
  111. ``get_absolute_url()`` and ``item_link()`` should return the
  112. item's URL as a normal Python string. As with ``get_absolute_url()``, the
  113. result of ``item_link()`` will be included directly in the URL, so you
  114. are responsible for doing all necessary URL quoting and conversion to
  115. ASCII inside the method itself.
  116. .. _chicagocrime.org: http://www.chicagocrime.org/
  117. A complex example
  118. -----------------
  119. The framework also supports more complex feeds, via arguments.
  120. For example, `chicagocrime.org`_ offers an RSS feed of recent crimes for every
  121. police beat in Chicago. It'd be silly to create a separate
  122. :class:`~django.contrib.syndication.views.Feed` class for each police beat; that
  123. would violate the :ref:`DRY principle <dry>` and would couple data to
  124. programming logic. Instead, the syndication framework lets you access the
  125. arguments passed from your :doc:`URLconf </topics/http/urls>` so feeds can output
  126. items based on information in the feed's URL.
  127. On chicagocrime.org, the police-beat feeds are accessible via URLs like this:
  128. * :file:`/beats/613/rss/` -- Returns recent crimes for beat 613.
  129. * :file:`/beats/1424/rss/` -- Returns recent crimes for beat 1424.
  130. These can be matched with a :doc:`URLconf </topics/http/urls>` line such as::
  131. (r'^beats/(?P<beat_id>\d+)/rss/$', BeatFeed()),
  132. Like a view, the arguments in the URL are passed to the ``get_object()``
  133. method along with the request object.
  134. .. versionchanged:: 1.2
  135. Prior to version 1.2, ``get_object()`` only accepted a ``bits`` argument.
  136. Here's the code for these beat-specific feeds::
  137. from django.contrib.syndication.views import FeedDoesNotExist
  138. from django.shortcuts import get_object_or_404
  139. class BeatFeed(Feed):
  140. description_template = 'feeds/beat_description.html'
  141. def get_object(self, request, beat_id):
  142. return get_object_or_404(Beat, pk=beat_id)
  143. def title(self, obj):
  144. return "Chicagocrime.org: Crimes for beat %s" % obj.beat
  145. def link(self, obj):
  146. return obj.get_absolute_url()
  147. def description(self, obj):
  148. return "Crimes recently reported in police beat %s" % obj.beat
  149. def items(self, obj):
  150. return Crime.objects.filter(beat=obj).order_by('-crime_date')[:30]
  151. To generate the feed's ``<title>``, ``<link>`` and ``<description>``, Django
  152. uses the ``title()``, ``link()`` and ``description()`` methods. In
  153. the previous example, they were simple string class attributes, but this example
  154. illustrates that they can be either strings *or* methods. For each of
  155. ``title``, ``link`` and ``description``, Django follows this
  156. algorithm:
  157. * First, it tries to call a method, passing the ``obj`` argument, where
  158. ``obj`` is the object returned by ``get_object()``.
  159. * Failing that, it tries to call a method with no arguments.
  160. * Failing that, it uses the class attribute.
  161. Also note that ``items()`` also follows the same algorithm -- first, it
  162. tries ``items(obj)``, then ``items()``, then finally an ``items``
  163. class attribute (which should be a list).
  164. We are using a template for the item descriptions. It can be very simple:
  165. .. code-block:: html+django
  166. {{ obj.description }}
  167. However, you are free to add formatting as desired.
  168. The ``ExampleFeed`` class below gives full documentation on methods and
  169. attributes of :class:`~django.contrib.syndication.views.Feed` classes.
  170. Specifying the type of feed
  171. ---------------------------
  172. By default, feeds produced in this framework use RSS 2.0.
  173. To change that, add a ``feed_type`` attribute to your
  174. :class:`~django.contrib.syndication.views.Feed` class, like so::
  175. from django.utils.feedgenerator import Atom1Feed
  176. class MyFeed(Feed):
  177. feed_type = Atom1Feed
  178. Note that you set ``feed_type`` to a class object, not an instance.
  179. Currently available feed types are:
  180. * :class:`django.utils.feedgenerator.Rss201rev2Feed` (RSS 2.01. Default.)
  181. * :class:`django.utils.feedgenerator.RssUserland091Feed` (RSS 0.91.)
  182. * :class:`django.utils.feedgenerator.Atom1Feed` (Atom 1.0.)
  183. Enclosures
  184. ----------
  185. To specify enclosures, such as those used in creating podcast feeds, use the
  186. ``item_enclosure_url``, ``item_enclosure_length`` and
  187. ``item_enclosure_mime_type`` hooks. See the ``ExampleFeed`` class below for
  188. usage examples.
  189. Language
  190. --------
  191. Feeds created by the syndication framework automatically include the
  192. appropriate ``<language>`` tag (RSS 2.0) or ``xml:lang`` attribute (Atom). This
  193. comes directly from your :setting:`LANGUAGE_CODE` setting.
  194. URLs
  195. ----
  196. The ``link`` method/attribute can return either an absolute path (e.g.
  197. :file:`"/blog/"`) or a URL with the fully-qualified domain and protocol (e.g.
  198. ``"http://www.example.com/blog/"``). If ``link`` doesn't return the domain,
  199. the syndication framework will insert the domain of the current site, according
  200. to your :setting:`SITE_ID setting <SITE_ID>`.
  201. Atom feeds require a ``<link rel="self">`` that defines the feed's current
  202. location. The syndication framework populates this automatically, using the
  203. domain of the current site according to the :setting:`SITE_ID` setting.
  204. Publishing Atom and RSS feeds in tandem
  205. ---------------------------------------
  206. Some developers like to make available both Atom *and* RSS versions of their
  207. feeds. That's easy to do with Django: Just create a subclass of your
  208. :class:`~django.contrib.syndication.views.Feed`
  209. class and set the ``feed_type`` to something different. Then update your
  210. URLconf to add the extra versions.
  211. Here's a full example::
  212. from django.contrib.syndication.views import Feed
  213. from chicagocrime.models import NewsItem
  214. from django.utils.feedgenerator import Atom1Feed
  215. class RssSiteNewsFeed(Feed):
  216. title = "Chicagocrime.org site news"
  217. link = "/sitenews/"
  218. description = "Updates on changes and additions to chicagocrime.org."
  219. def items(self):
  220. return NewsItem.objects.order_by('-pub_date')[:5]
  221. class AtomSiteNewsFeed(RssSiteNewsFeed):
  222. feed_type = Atom1Feed
  223. subtitle = RssSiteNewsFeed.description
  224. .. Note::
  225. In this example, the RSS feed uses a ``description`` while the Atom
  226. feed uses a ``subtitle``. That's because Atom feeds don't provide for
  227. a feed-level "description," but they *do* provide for a "subtitle."
  228. If you provide a ``description`` in your
  229. :class:`~django.contrib.syndication.views.Feed` class, Django will *not*
  230. automatically put that into the ``subtitle`` element, because a
  231. subtitle and description are not necessarily the same thing. Instead, you
  232. should define a ``subtitle`` attribute.
  233. In the above example, we simply set the Atom feed's ``subtitle`` to the
  234. RSS feed's ``description``, because it's quite short already.
  235. And the accompanying URLconf::
  236. from django.conf.urls import patterns, url, include
  237. from myproject.feeds import RssSiteNewsFeed, AtomSiteNewsFeed
  238. urlpatterns = patterns('',
  239. # ...
  240. (r'^sitenews/rss/$', RssSiteNewsFeed()),
  241. (r'^sitenews/atom/$', AtomSiteNewsFeed()),
  242. # ...
  243. )
  244. Feed class reference
  245. --------------------
  246. .. class:: django.contrib.syndication.views.Feed
  247. This example illustrates all possible attributes and methods for a
  248. :class:`~django.contrib.syndication.views.Feed` class::
  249. from django.contrib.syndication.views import Feed
  250. from django.utils import feedgenerator
  251. class ExampleFeed(Feed):
  252. # FEED TYPE -- Optional. This should be a class that subclasses
  253. # django.utils.feedgenerator.SyndicationFeed. This designates
  254. # which type of feed this should be: RSS 2.0, Atom 1.0, etc. If
  255. # you don't specify feed_type, your feed will be RSS 2.0. This
  256. # should be a class, not an instance of the class.
  257. feed_type = feedgenerator.Rss201rev2Feed
  258. # TEMPLATE NAMES -- Optional. These should be strings
  259. # representing names of Django templates that the system should
  260. # use in rendering the title and description of your feed items.
  261. # Both are optional. If a template is not specified, the
  262. # item_title() or item_description() methods are used instead.
  263. title_template = None
  264. description_template = None
  265. # TITLE -- One of the following three is required. The framework
  266. # looks for them in this order.
  267. def title(self, obj):
  268. """
  269. Takes the object returned by get_object() and returns the
  270. feed's title as a normal Python string.
  271. """
  272. def title(self):
  273. """
  274. Returns the feed's title as a normal Python string.
  275. """
  276. title = 'foo' # Hard-coded title.
  277. # LINK -- One of the following three is required. The framework
  278. # looks for them in this order.
  279. def link(self, obj):
  280. """
  281. # Takes the object returned by get_object() and returns the URL
  282. # of the HTML version of the feed as a normal Python string.
  283. """
  284. def link(self):
  285. """
  286. Returns the URL of the HTML version of the feed as a normal Python
  287. string.
  288. """
  289. link = '/blog/' # Hard-coded URL.
  290. # FEED_URL -- One of the following three is optional. The framework
  291. # looks for them in this order.
  292. def feed_url(self, obj):
  293. """
  294. # Takes the object returned by get_object() and returns the feed's
  295. # own URL as a normal Python string.
  296. """
  297. def feed_url(self):
  298. """
  299. Returns the feed's own URL as a normal Python string.
  300. """
  301. feed_url = '/blog/rss/' # Hard-coded URL.
  302. # GUID -- One of the following three is optional. The framework looks
  303. # for them in this order. This property is only used for Atom feeds
  304. # (where it is the feed-level ID element). If not provided, the feed
  305. # link is used as the ID.
  306. def feed_guid(self, obj):
  307. """
  308. Takes the object returned by get_object() and returns the globally
  309. unique ID for the feed as a normal Python string.
  310. """
  311. def feed_guid(self):
  312. """
  313. Returns the feed's globally unique ID as a normal Python string.
  314. """
  315. feed_guid = '/foo/bar/1234' # Hard-coded guid.
  316. # DESCRIPTION -- One of the following three is required. The framework
  317. # looks for them in this order.
  318. def description(self, obj):
  319. """
  320. Takes the object returned by get_object() and returns the feed's
  321. description as a normal Python string.
  322. """
  323. def description(self):
  324. """
  325. Returns the feed's description as a normal Python string.
  326. """
  327. description = 'Foo bar baz.' # Hard-coded description.
  328. # AUTHOR NAME --One of the following three is optional. The framework
  329. # looks for them in this order.
  330. def author_name(self, obj):
  331. """
  332. Takes the object returned by get_object() and returns the feed's
  333. author's name as a normal Python string.
  334. """
  335. def author_name(self):
  336. """
  337. Returns the feed's author's name as a normal Python string.
  338. """
  339. author_name = 'Sally Smith' # Hard-coded author name.
  340. # AUTHOR E-MAIL --One of the following three is optional. The framework
  341. # looks for them in this order.
  342. def author_email(self, obj):
  343. """
  344. Takes the object returned by get_object() and returns the feed's
  345. author's email as a normal Python string.
  346. """
  347. def author_email(self):
  348. """
  349. Returns the feed's author's email as a normal Python string.
  350. """
  351. author_email = 'test@example.com' # Hard-coded author email.
  352. # AUTHOR LINK --One of the following three is optional. The framework
  353. # looks for them in this order. In each case, the URL should include
  354. # the "http://" and domain name.
  355. def author_link(self, obj):
  356. """
  357. Takes the object returned by get_object() and returns the feed's
  358. author's URL as a normal Python string.
  359. """
  360. def author_link(self):
  361. """
  362. Returns the feed's author's URL as a normal Python string.
  363. """
  364. author_link = 'http://www.example.com/' # Hard-coded author URL.
  365. # CATEGORIES -- One of the following three is optional. The framework
  366. # looks for them in this order. In each case, the method/attribute
  367. # should return an iterable object that returns strings.
  368. def categories(self, obj):
  369. """
  370. Takes the object returned by get_object() and returns the feed's
  371. categories as iterable over strings.
  372. """
  373. def categories(self):
  374. """
  375. Returns the feed's categories as iterable over strings.
  376. """
  377. categories = ("python", "django") # Hard-coded list of categories.
  378. # COPYRIGHT NOTICE -- One of the following three is optional. The
  379. # framework looks for them in this order.
  380. def feed_copyright(self, obj):
  381. """
  382. Takes the object returned by get_object() and returns the feed's
  383. copyright notice as a normal Python string.
  384. """
  385. def feed_copyright(self):
  386. """
  387. Returns the feed's copyright notice as a normal Python string.
  388. """
  389. feed_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
  390. # TTL -- One of the following three is optional. The framework looks
  391. # for them in this order. Ignored for Atom feeds.
  392. def ttl(self, obj):
  393. """
  394. Takes the object returned by get_object() and returns the feed's
  395. TTL (Time To Live) as a normal Python string.
  396. """
  397. def ttl(self):
  398. """
  399. Returns the feed's TTL as a normal Python string.
  400. """
  401. ttl = 600 # Hard-coded Time To Live.
  402. # ITEMS -- One of the following three is required. The framework looks
  403. # for them in this order.
  404. def items(self, obj):
  405. """
  406. Takes the object returned by get_object() and returns a list of
  407. items to publish in this feed.
  408. """
  409. def items(self):
  410. """
  411. Returns a list of items to publish in this feed.
  412. """
  413. items = ('Item 1', 'Item 2') # Hard-coded items.
  414. # GET_OBJECT -- This is required for feeds that publish different data
  415. # for different URL parameters. (See "A complex example" above.)
  416. def get_object(self, request, *args, **kwargs):
  417. """
  418. Takes the current request and the arguments from the URL, and
  419. returns an object represented by this feed. Raises
  420. django.core.exceptions.ObjectDoesNotExist on error.
  421. """
  422. # ITEM TITLE AND DESCRIPTION -- If title_template or
  423. # description_template are not defined, these are used instead. Both are
  424. # optional, by default they will use the unicode representation of the
  425. # item.
  426. def item_title(self, item):
  427. """
  428. Takes an item, as returned by items(), and returns the item's
  429. title as a normal Python string.
  430. """
  431. def item_title(self):
  432. """
  433. Returns the title for every item in the feed.
  434. """
  435. item_title = 'Breaking News: Nothing Happening' # Hard-coded title.
  436. def item_description(self, item):
  437. """
  438. Takes an item, as returned by items(), and returns the item's
  439. description as a normal Python string.
  440. """
  441. def item_description(self):
  442. """
  443. Returns the description for every item in the feed.
  444. """
  445. item_description = 'A description of the item.' # Hard-coded description.
  446. # ITEM LINK -- One of these three is required. The framework looks for
  447. # them in this order.
  448. # First, the framework tries the two methods below, in
  449. # order. Failing that, it falls back to the get_absolute_url()
  450. # method on each item returned by items().
  451. def item_link(self, item):
  452. """
  453. Takes an item, as returned by items(), and returns the item's URL.
  454. """
  455. def item_link(self):
  456. """
  457. Returns the URL for every item in the feed.
  458. """
  459. # ITEM_GUID -- The following method is optional. If not provided, the
  460. # item's link is used by default.
  461. def item_guid(self, obj):
  462. """
  463. Takes an item, as return by items(), and returns the item's ID.
  464. """
  465. # ITEM AUTHOR NAME -- One of the following three is optional. The
  466. # framework looks for them in this order.
  467. def item_author_name(self, item):
  468. """
  469. Takes an item, as returned by items(), and returns the item's
  470. author's name as a normal Python string.
  471. """
  472. def item_author_name(self):
  473. """
  474. Returns the author name for every item in the feed.
  475. """
  476. item_author_name = 'Sally Smith' # Hard-coded author name.
  477. # ITEM AUTHOR E-MAIL --One of the following three is optional. The
  478. # framework looks for them in this order.
  479. #
  480. # If you specify this, you must specify item_author_name.
  481. def item_author_email(self, obj):
  482. """
  483. Takes an item, as returned by items(), and returns the item's
  484. author's email as a normal Python string.
  485. """
  486. def item_author_email(self):
  487. """
  488. Returns the author email for every item in the feed.
  489. """
  490. item_author_email = 'test@example.com' # Hard-coded author email.
  491. # ITEM AUTHOR LINK -- One of the following three is optional. The
  492. # framework looks for them in this order. In each case, the URL should
  493. # include the "http://" and domain name.
  494. #
  495. # If you specify this, you must specify item_author_name.
  496. def item_author_link(self, obj):
  497. """
  498. Takes an item, as returned by items(), and returns the item's
  499. author's URL as a normal Python string.
  500. """
  501. def item_author_link(self):
  502. """
  503. Returns the author URL for every item in the feed.
  504. """
  505. item_author_link = 'http://www.example.com/' # Hard-coded author URL.
  506. # ITEM ENCLOSURE URL -- One of these three is required if you're
  507. # publishing enclosures. The framework looks for them in this order.
  508. def item_enclosure_url(self, item):
  509. """
  510. Takes an item, as returned by items(), and returns the item's
  511. enclosure URL.
  512. """
  513. def item_enclosure_url(self):
  514. """
  515. Returns the enclosure URL for every item in the feed.
  516. """
  517. item_enclosure_url = "/foo/bar.mp3" # Hard-coded enclosure link.
  518. # ITEM ENCLOSURE LENGTH -- One of these three is required if you're
  519. # publishing enclosures. The framework looks for them in this order.
  520. # In each case, the returned value should be either an integer, or a
  521. # string representation of the integer, in bytes.
  522. def item_enclosure_length(self, item):
  523. """
  524. Takes an item, as returned by items(), and returns the item's
  525. enclosure length.
  526. """
  527. def item_enclosure_length(self):
  528. """
  529. Returns the enclosure length for every item in the feed.
  530. """
  531. item_enclosure_length = 32000 # Hard-coded enclosure length.
  532. # ITEM ENCLOSURE MIME TYPE -- One of these three is required if you're
  533. # publishing enclosures. The framework looks for them in this order.
  534. def item_enclosure_mime_type(self, item):
  535. """
  536. Takes an item, as returned by items(), and returns the item's
  537. enclosure MIME type.
  538. """
  539. def item_enclosure_mime_type(self):
  540. """
  541. Returns the enclosure MIME type for every item in the feed.
  542. """
  543. item_enclosure_mime_type = "audio/mpeg" # Hard-coded enclosure MIME type.
  544. # ITEM PUBDATE -- It's optional to use one of these three. This is a
  545. # hook that specifies how to get the pubdate for a given item.
  546. # In each case, the method/attribute should return a Python
  547. # datetime.datetime object.
  548. def item_pubdate(self, item):
  549. """
  550. Takes an item, as returned by items(), and returns the item's
  551. pubdate.
  552. """
  553. def item_pubdate(self):
  554. """
  555. Returns the pubdate for every item in the feed.
  556. """
  557. item_pubdate = datetime.datetime(2005, 5, 3) # Hard-coded pubdate.
  558. # ITEM CATEGORIES -- It's optional to use one of these three. This is
  559. # a hook that specifies how to get the list of categories for a given
  560. # item. In each case, the method/attribute should return an iterable
  561. # object that returns strings.
  562. def item_categories(self, item):
  563. """
  564. Takes an item, as returned by items(), and returns the item's
  565. categories.
  566. """
  567. def item_categories(self):
  568. """
  569. Returns the categories for every item in the feed.
  570. """
  571. item_categories = ("python", "django") # Hard-coded categories.
  572. # ITEM COPYRIGHT NOTICE (only applicable to Atom feeds) -- One of the
  573. # following three is optional. The framework looks for them in this
  574. # order.
  575. def item_copyright(self, obj):
  576. """
  577. Takes an item, as returned by items(), and returns the item's
  578. copyright notice as a normal Python string.
  579. """
  580. def item_copyright(self):
  581. """
  582. Returns the copyright notice for every item in the feed.
  583. """
  584. item_copyright = 'Copyright (c) 2007, Sally Smith' # Hard-coded copyright notice.
  585. The low-level framework
  586. =======================
  587. Behind the scenes, the high-level RSS framework uses a lower-level framework
  588. for generating feeds' XML. This framework lives in a single module:
  589. `django/utils/feedgenerator.py`_.
  590. You use this framework on your own, for lower-level feed generation. You can
  591. also create custom feed generator subclasses for use with the ``feed_type``
  592. ``Feed`` option.
  593. .. currentmodule:: django.utils.feedgenerator
  594. ``SyndicationFeed`` classes
  595. ---------------------------
  596. The :mod:`~django.utils.feedgenerator` module contains a base class:
  597. * :class:`django.utils.feedgenerator.SyndicationFeed`
  598. and several subclasses:
  599. * :class:`django.utils.feedgenerator.RssUserland091Feed`
  600. * :class:`django.utils.feedgenerator.Rss201rev2Feed`
  601. * :class:`django.utils.feedgenerator.Atom1Feed`
  602. Each of these three classes knows how to render a certain type of feed as XML.
  603. They share this interface:
  604. :meth:`.SyndicationFeed.__init__`
  605. Initialize the feed with the given dictionary of metadata, which applies to
  606. the entire feed. Required keyword arguments are:
  607. * ``title``
  608. * ``link``
  609. * ``description``
  610. There's also a bunch of other optional keywords:
  611. * ``language``
  612. * ``author_email``
  613. * ``author_name``
  614. * ``author_link``
  615. * ``subtitle``
  616. * ``categories``
  617. * ``feed_url``
  618. * ``feed_copyright``
  619. * ``feed_guid``
  620. * ``ttl``
  621. Any extra keyword arguments you pass to ``__init__`` will be stored in
  622. ``self.feed`` for use with `custom feed generators`_.
  623. All parameters should be Unicode objects, except ``categories``, which
  624. should be a sequence of Unicode objects.
  625. :meth:`.SyndicationFeed.add_item`
  626. Add an item to the feed with the given parameters.
  627. Required keyword arguments are:
  628. * ``title``
  629. * ``link``
  630. * ``description``
  631. Optional keyword arguments are:
  632. * ``author_email``
  633. * ``author_name``
  634. * ``author_link``
  635. * ``pubdate``
  636. * ``comments``
  637. * ``unique_id``
  638. * ``enclosure``
  639. * ``categories``
  640. * ``item_copyright``
  641. * ``ttl``
  642. Extra keyword arguments will be stored for `custom feed generators`_.
  643. All parameters, if given, should be Unicode objects, except:
  644. * ``pubdate`` should be a Python :class:`~datetime.datetime` object.
  645. * ``enclosure`` should be an instance of
  646. :class:`django.utils.feedgenerator.Enclosure`.
  647. * ``categories`` should be a sequence of Unicode objects.
  648. :meth:`.SyndicationFeed.write`
  649. Outputs the feed in the given encoding to outfile, which is a file-like object.
  650. :meth:`.SyndicationFeed.writeString`
  651. Returns the feed as a string in the given encoding.
  652. For example, to create an Atom 1.0 feed and print it to standard output::
  653. >>> from django.utils import feedgenerator
  654. >>> from datetime import datetime
  655. >>> f = feedgenerator.Atom1Feed(
  656. ... title=u"My Weblog",
  657. ... link=u"http://www.example.com/",
  658. ... description=u"In which I write about what I ate today.",
  659. ... language=u"en",
  660. ... author_name=u"Myself",
  661. ... feed_url=u"http://example.com/atom.xml")
  662. >>> f.add_item(title=u"Hot dog today",
  663. ... link=u"http://www.example.com/entries/1/",
  664. ... pubdate=datetime.now(),
  665. ... description=u"<p>Today I had a Vienna Beef hot dog. It was pink, plump and perfect.</p>")
  666. >>> print(f.writeString('UTF-8'))
  667. <?xml version="1.0" encoding="UTF-8"?>
  668. <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  669. ...
  670. </feed>
  671. .. _django/utils/feedgenerator.py: https://github.com/django/django/blob/master/django/utils/feedgenerator.py
  672. .. currentmodule:: django.contrib.syndication
  673. Custom feed generators
  674. ----------------------
  675. If you need to produce a custom feed format, you've got a couple of options.
  676. If the feed format is totally custom, you'll want to subclass
  677. ``SyndicationFeed`` and completely replace the ``write()`` and
  678. ``writeString()`` methods.
  679. However, if the feed format is a spin-off of RSS or Atom (i.e. GeoRSS_, Apple's
  680. `iTunes podcast format`_, etc.), you've got a better choice. These types of
  681. feeds typically add extra elements and/or attributes to the underlying format,
  682. and there are a set of methods that ``SyndicationFeed`` calls to get these extra
  683. attributes. Thus, you can subclass the appropriate feed generator class
  684. (``Atom1Feed`` or ``Rss201rev2Feed``) and extend these callbacks. They are:
  685. .. _georss: http://georss.org/
  686. .. _itunes podcast format: http://www.apple.com/itunes/podcasts/specs.html
  687. ``SyndicationFeed.root_attributes(self, )``
  688. Return a ``dict`` of attributes to add to the root feed element
  689. (``feed``/``channel``).
  690. ``SyndicationFeed.add_root_elements(self, handler)``
  691. Callback to add elements inside the root feed element
  692. (``feed``/``channel``). ``handler`` is an
  693. :class:`~xml.sax.saxutils.XMLGenerator` from Python's built-in SAX library;
  694. you'll call methods on it to add to the XML document in process.
  695. ``SyndicationFeed.item_attributes(self, item)``
  696. Return a ``dict`` of attributes to add to each item (``item``/``entry``)
  697. element. The argument, ``item``, is a dictionary of all the data passed to
  698. ``SyndicationFeed.add_item()``.
  699. ``SyndicationFeed.add_item_elements(self, handler, item)``
  700. Callback to add elements to each item (``item``/``entry``) element.
  701. ``handler`` and ``item`` are as above.
  702. .. warning::
  703. If you override any of these methods, be sure to call the superclass methods
  704. since they add the required elements for each feed format.
  705. For example, you might start implementing an iTunes RSS feed generator like so::
  706. class iTunesFeed(Rss201rev2Feed):
  707. def root_attributes(self):
  708. attrs = super(iTunesFeed, self).root_attributes()
  709. attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
  710. return attrs
  711. def add_root_elements(self, handler):
  712. super(iTunesFeed, self).add_root_elements(handler)
  713. handler.addQuickElement('itunes:explicit', 'clean')
  714. Obviously there's a lot more work to be done for a complete custom feed class,
  715. but the above example should demonstrate the basic idea.