You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

feedgenerator.py 17 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. """
  2. Syndication feed generation library -- used for generating RSS, etc.
  3. Sample usage:
  4. >>> from django.utils import feedgenerator
  5. >>> feed = feedgenerator.Rss201rev2Feed(
  6. ... title="Poynter E-Media Tidbits",
  7. ... link="http://www.poynter.org/column.asp?id=31",
  8. ... description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
  9. ... language="en",
  10. ... )
  11. >>> feed.add_item(
  12. ... title="Hello",
  13. ... link="http://www.holovaty.com/test/",
  14. ... description="Testing."
  15. ... )
  16. >>> with open('test.rss', 'w') as fp:
  17. ... feed.write(fp, 'utf-8')
  18. For definitions of the different versions of RSS, see:
  19. http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
  20. """
  21. from __future__ import unicode_literals
  22. import datetime
  23. import warnings
  24. from django.utils import datetime_safe, six
  25. from django.utils.deprecation import RemovedInDjango20Warning
  26. from django.utils.encoding import force_text, iri_to_uri
  27. from django.utils.six import StringIO
  28. from django.utils.six.moves.urllib.parse import urlparse
  29. from django.utils.xmlutils import SimplerXMLGenerator
  30. def rfc2822_date(date):
  31. # We can't use strftime() because it produces locale-dependent results, so
  32. # we have to map english month and day names manually
  33. months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',)
  34. days = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
  35. # Support datetime objects older than 1900
  36. date = datetime_safe.new_datetime(date)
  37. # We do this ourselves to be timezone aware, email.Utils is not tz aware.
  38. dow = days[date.weekday()]
  39. month = months[date.month - 1]
  40. time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month))
  41. if six.PY2: # strftime returns a byte string in Python 2
  42. time_str = time_str.decode('utf-8')
  43. offset = date.utcoffset()
  44. # Historically, this function assumes that naive datetimes are in UTC.
  45. if offset is None:
  46. return time_str + '-0000'
  47. else:
  48. timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
  49. hour, minute = divmod(timezone, 60)
  50. return time_str + '%+03d%02d' % (hour, minute)
  51. def rfc3339_date(date):
  52. # Support datetime objects older than 1900
  53. date = datetime_safe.new_datetime(date)
  54. time_str = date.strftime('%Y-%m-%dT%H:%M:%S')
  55. if six.PY2: # strftime returns a byte string in Python 2
  56. time_str = time_str.decode('utf-8')
  57. offset = date.utcoffset()
  58. # Historically, this function assumes that naive datetimes are in UTC.
  59. if offset is None:
  60. return time_str + 'Z'
  61. else:
  62. timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
  63. hour, minute = divmod(timezone, 60)
  64. return time_str + '%+03d:%02d' % (hour, minute)
  65. def get_tag_uri(url, date):
  66. """
  67. Creates a TagURI.
  68. See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  69. """
  70. bits = urlparse(url)
  71. d = ''
  72. if date is not None:
  73. d = ',%s' % datetime_safe.new_datetime(date).strftime('%Y-%m-%d')
  74. return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment)
  75. class SyndicationFeed(object):
  76. "Base class for all syndication feeds. Subclasses should provide write()"
  77. def __init__(self, title, link, description, language=None, author_email=None,
  78. author_name=None, author_link=None, subtitle=None, categories=None,
  79. feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs):
  80. to_unicode = lambda s: force_text(s, strings_only=True)
  81. if categories:
  82. categories = [force_text(c) for c in categories]
  83. if ttl is not None:
  84. # Force ints to unicode
  85. ttl = force_text(ttl)
  86. self.feed = {
  87. 'title': to_unicode(title),
  88. 'link': iri_to_uri(link),
  89. 'description': to_unicode(description),
  90. 'language': to_unicode(language),
  91. 'author_email': to_unicode(author_email),
  92. 'author_name': to_unicode(author_name),
  93. 'author_link': iri_to_uri(author_link),
  94. 'subtitle': to_unicode(subtitle),
  95. 'categories': categories or (),
  96. 'feed_url': iri_to_uri(feed_url),
  97. 'feed_copyright': to_unicode(feed_copyright),
  98. 'id': feed_guid or link,
  99. 'ttl': ttl,
  100. }
  101. self.feed.update(kwargs)
  102. self.items = []
  103. def add_item(self, title, link, description, author_email=None,
  104. author_name=None, author_link=None, pubdate=None, comments=None,
  105. unique_id=None, unique_id_is_permalink=None, enclosure=None,
  106. categories=(), item_copyright=None, ttl=None, updateddate=None,
  107. enclosures=None, **kwargs):
  108. """
  109. Adds an item to the feed. All args are expected to be Python Unicode
  110. objects except pubdate and updateddate, which are datetime.datetime
  111. objects, and enclosures, which is an iterable of instances of the
  112. Enclosure class.
  113. """
  114. to_unicode = lambda s: force_text(s, strings_only=True)
  115. if categories:
  116. categories = [to_unicode(c) for c in categories]
  117. if ttl is not None:
  118. # Force ints to unicode
  119. ttl = force_text(ttl)
  120. if enclosure is None:
  121. enclosures = [] if enclosures is None else enclosures
  122. else:
  123. warnings.warn(
  124. "The enclosure keyword argument is deprecated, "
  125. "use enclosures instead.",
  126. RemovedInDjango20Warning,
  127. stacklevel=2,
  128. )
  129. enclosures = [enclosure]
  130. item = {
  131. 'title': to_unicode(title),
  132. 'link': iri_to_uri(link),
  133. 'description': to_unicode(description),
  134. 'author_email': to_unicode(author_email),
  135. 'author_name': to_unicode(author_name),
  136. 'author_link': iri_to_uri(author_link),
  137. 'pubdate': pubdate,
  138. 'updateddate': updateddate,
  139. 'comments': to_unicode(comments),
  140. 'unique_id': to_unicode(unique_id),
  141. 'unique_id_is_permalink': unique_id_is_permalink,
  142. 'enclosures': enclosures,
  143. 'categories': categories or (),
  144. 'item_copyright': to_unicode(item_copyright),
  145. 'ttl': ttl,
  146. }
  147. item.update(kwargs)
  148. self.items.append(item)
  149. def num_items(self):
  150. return len(self.items)
  151. def root_attributes(self):
  152. """
  153. Return extra attributes to place on the root (i.e. feed/channel) element.
  154. Called from write().
  155. """
  156. return {}
  157. def add_root_elements(self, handler):
  158. """
  159. Add elements in the root (i.e. feed/channel) element. Called
  160. from write().
  161. """
  162. pass
  163. def item_attributes(self, item):
  164. """
  165. Return extra attributes to place on each item (i.e. item/entry) element.
  166. """
  167. return {}
  168. def add_item_elements(self, handler, item):
  169. """
  170. Add elements on each item (i.e. item/entry) element.
  171. """
  172. pass
  173. def write(self, outfile, encoding):
  174. """
  175. Outputs the feed in the given encoding to outfile, which is a file-like
  176. object. Subclasses should override this.
  177. """
  178. raise NotImplementedError('subclasses of SyndicationFeed must provide a write() method')
  179. def writeString(self, encoding):
  180. """
  181. Returns the feed in the given encoding as a string.
  182. """
  183. s = StringIO()
  184. self.write(s, encoding)
  185. return s.getvalue()
  186. def latest_post_date(self):
  187. """
  188. Returns the latest item's pubdate or updateddate. If no items
  189. have either of these attributes this returns the current date/time.
  190. """
  191. latest_date = None
  192. date_keys = ('updateddate', 'pubdate')
  193. for item in self.items:
  194. for date_key in date_keys:
  195. item_date = item.get(date_key)
  196. if item_date:
  197. if latest_date is None or item_date > latest_date:
  198. latest_date = item_date
  199. return latest_date or datetime.datetime.now()
  200. class Enclosure(object):
  201. "Represents an RSS enclosure"
  202. def __init__(self, url, length, mime_type):
  203. "All args are expected to be Python Unicode objects"
  204. self.length, self.mime_type = length, mime_type
  205. self.url = iri_to_uri(url)
  206. class RssFeed(SyndicationFeed):
  207. content_type = 'application/rss+xml; charset=utf-8'
  208. def write(self, outfile, encoding):
  209. handler = SimplerXMLGenerator(outfile, encoding)
  210. handler.startDocument()
  211. handler.startElement("rss", self.rss_attributes())
  212. handler.startElement("channel", self.root_attributes())
  213. self.add_root_elements(handler)
  214. self.write_items(handler)
  215. self.endChannelElement(handler)
  216. handler.endElement("rss")
  217. def rss_attributes(self):
  218. return {"version": self._version,
  219. "xmlns:atom": "http://www.w3.org/2005/Atom"}
  220. def write_items(self, handler):
  221. for item in self.items:
  222. handler.startElement('item', self.item_attributes(item))
  223. self.add_item_elements(handler, item)
  224. handler.endElement("item")
  225. def add_root_elements(self, handler):
  226. handler.addQuickElement("title", self.feed['title'])
  227. handler.addQuickElement("link", self.feed['link'])
  228. handler.addQuickElement("description", self.feed['description'])
  229. if self.feed['feed_url'] is not None:
  230. handler.addQuickElement("atom:link", None,
  231. {"rel": "self", "href": self.feed['feed_url']})
  232. if self.feed['language'] is not None:
  233. handler.addQuickElement("language", self.feed['language'])
  234. for cat in self.feed['categories']:
  235. handler.addQuickElement("category", cat)
  236. if self.feed['feed_copyright'] is not None:
  237. handler.addQuickElement("copyright", self.feed['feed_copyright'])
  238. handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date()))
  239. if self.feed['ttl'] is not None:
  240. handler.addQuickElement("ttl", self.feed['ttl'])
  241. def endChannelElement(self, handler):
  242. handler.endElement("channel")
  243. @property
  244. def mime_type(self):
  245. warnings.warn(
  246. 'The mime_type attribute of RssFeed is deprecated. '
  247. 'Use content_type instead.',
  248. RemovedInDjango20Warning, stacklevel=2
  249. )
  250. return self.content_type
  251. class RssUserland091Feed(RssFeed):
  252. _version = "0.91"
  253. def add_item_elements(self, handler, item):
  254. handler.addQuickElement("title", item['title'])
  255. handler.addQuickElement("link", item['link'])
  256. if item['description'] is not None:
  257. handler.addQuickElement("description", item['description'])
  258. class Rss201rev2Feed(RssFeed):
  259. # Spec: http://blogs.law.harvard.edu/tech/rss
  260. _version = "2.0"
  261. def add_item_elements(self, handler, item):
  262. handler.addQuickElement("title", item['title'])
  263. handler.addQuickElement("link", item['link'])
  264. if item['description'] is not None:
  265. handler.addQuickElement("description", item['description'])
  266. # Author information.
  267. if item["author_name"] and item["author_email"]:
  268. handler.addQuickElement("author", "%s (%s)" %
  269. (item['author_email'], item['author_name']))
  270. elif item["author_email"]:
  271. handler.addQuickElement("author", item["author_email"])
  272. elif item["author_name"]:
  273. handler.addQuickElement("dc:creator", item["author_name"],
  274. {"xmlns:dc": "http://purl.org/dc/elements/1.1/"})
  275. if item['pubdate'] is not None:
  276. handler.addQuickElement("pubDate", rfc2822_date(item['pubdate']))
  277. if item['comments'] is not None:
  278. handler.addQuickElement("comments", item['comments'])
  279. if item['unique_id'] is not None:
  280. guid_attrs = {}
  281. if isinstance(item.get('unique_id_is_permalink'), bool):
  282. guid_attrs['isPermaLink'] = str(
  283. item['unique_id_is_permalink']).lower()
  284. handler.addQuickElement("guid", item['unique_id'], guid_attrs)
  285. if item['ttl'] is not None:
  286. handler.addQuickElement("ttl", item['ttl'])
  287. # Enclosure.
  288. if item['enclosures']:
  289. enclosures = list(item['enclosures'])
  290. if len(enclosures) > 1:
  291. raise ValueError(
  292. "RSS feed items may only have one enclosure, see "
  293. "http://www.rssboard.org/rss-profile#element-channel-item-enclosure"
  294. )
  295. enclosure = enclosures[0]
  296. handler.addQuickElement('enclosure', '', {
  297. 'url': enclosure.url,
  298. 'length': enclosure.length,
  299. 'type': enclosure.mime_type,
  300. })
  301. # Categories.
  302. for cat in item['categories']:
  303. handler.addQuickElement("category", cat)
  304. class Atom1Feed(SyndicationFeed):
  305. # Spec: https://tools.ietf.org/html/rfc4287
  306. content_type = 'application/atom+xml; charset=utf-8'
  307. ns = "http://www.w3.org/2005/Atom"
  308. def write(self, outfile, encoding):
  309. handler = SimplerXMLGenerator(outfile, encoding)
  310. handler.startDocument()
  311. handler.startElement('feed', self.root_attributes())
  312. self.add_root_elements(handler)
  313. self.write_items(handler)
  314. handler.endElement("feed")
  315. def root_attributes(self):
  316. if self.feed['language'] is not None:
  317. return {"xmlns": self.ns, "xml:lang": self.feed['language']}
  318. else:
  319. return {"xmlns": self.ns}
  320. def add_root_elements(self, handler):
  321. handler.addQuickElement("title", self.feed['title'])
  322. handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']})
  323. if self.feed['feed_url'] is not None:
  324. handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']})
  325. handler.addQuickElement("id", self.feed['id'])
  326. handler.addQuickElement("updated", rfc3339_date(self.latest_post_date()))
  327. if self.feed['author_name'] is not None:
  328. handler.startElement("author", {})
  329. handler.addQuickElement("name", self.feed['author_name'])
  330. if self.feed['author_email'] is not None:
  331. handler.addQuickElement("email", self.feed['author_email'])
  332. if self.feed['author_link'] is not None:
  333. handler.addQuickElement("uri", self.feed['author_link'])
  334. handler.endElement("author")
  335. if self.feed['subtitle'] is not None:
  336. handler.addQuickElement("subtitle", self.feed['subtitle'])
  337. for cat in self.feed['categories']:
  338. handler.addQuickElement("category", "", {"term": cat})
  339. if self.feed['feed_copyright'] is not None:
  340. handler.addQuickElement("rights", self.feed['feed_copyright'])
  341. def write_items(self, handler):
  342. for item in self.items:
  343. handler.startElement("entry", self.item_attributes(item))
  344. self.add_item_elements(handler, item)
  345. handler.endElement("entry")
  346. def add_item_elements(self, handler, item):
  347. handler.addQuickElement("title", item['title'])
  348. handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"})
  349. if item['pubdate'] is not None:
  350. handler.addQuickElement('published', rfc3339_date(item['pubdate']))
  351. if item['updateddate'] is not None:
  352. handler.addQuickElement('updated', rfc3339_date(item['updateddate']))
  353. # Author information.
  354. if item['author_name'] is not None:
  355. handler.startElement("author", {})
  356. handler.addQuickElement("name", item['author_name'])
  357. if item['author_email'] is not None:
  358. handler.addQuickElement("email", item['author_email'])
  359. if item['author_link'] is not None:
  360. handler.addQuickElement("uri", item['author_link'])
  361. handler.endElement("author")
  362. # Unique ID.
  363. if item['unique_id'] is not None:
  364. unique_id = item['unique_id']
  365. else:
  366. unique_id = get_tag_uri(item['link'], item['pubdate'])
  367. handler.addQuickElement("id", unique_id)
  368. # Summary.
  369. if item['description'] is not None:
  370. handler.addQuickElement("summary", item['description'], {"type": "html"})
  371. # Enclosures.
  372. for enclosure in item['enclosures']:
  373. handler.addQuickElement('link', '', {
  374. 'rel': 'enclosure',
  375. 'href': enclosure.url,
  376. 'length': enclosure.length,
  377. 'type': enclosure.mime_type,
  378. })
  379. # Categories.
  380. for cat in item['categories']:
  381. handler.addQuickElement("category", "", {"term": cat})
  382. # Rights.
  383. if item['item_copyright'] is not None:
  384. handler.addQuickElement("rights", item['item_copyright'])
  385. @property
  386. def mime_type(self):
  387. warnings.warn(
  388. 'The mime_type attribute of Atom1Feed is deprecated. '
  389. 'Use content_type instead.',
  390. RemovedInDjango20Warning, stacklevel=2
  391. )
  392. return self.content_type
  393. # This isolates the decision of what the system default is, so calling code can
  394. # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed".
  395. DefaultFeed = Rss201rev2Feed