syndication.txt 37 KB

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