syndication.txt 33 KB

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