syndication.txt 34 KB

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