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 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
  20. """
  21. import datetime
  22. import email
  23. from io import StringIO
  24. from urllib.parse import urlparse
  25. from django.utils.encoding import iri_to_uri
  26. from django.utils.timezone import utc
  27. from django.utils.xmlutils import SimplerXMLGenerator
  28. def rfc2822_date(date):
  29. if not isinstance(date, datetime.datetime):
  30. date = datetime.datetime.combine(date, datetime.time())
  31. return email.utils.format_datetime(date)
  32. def rfc3339_date(date):
  33. if not isinstance(date, datetime.datetime):
  34. date = datetime.datetime.combine(date, datetime.time())
  35. return date.isoformat() + ('Z' if date.utcoffset() is None else '')
  36. def get_tag_uri(url, date):
  37. """
  38. Create a TagURI.
  39. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  40. """
  41. bits = urlparse(url)
  42. d = ''
  43. if date is not None:
  44. d = ',%s' % date.strftime('%Y-%m-%d')
  45. return 'tag:%s%s:%s/%s' % (bits.hostname, d, bits.path, bits.fragment)
  46. class SyndicationFeed:
  47. "Base class for all syndication feeds. Subclasses should provide write()"
  48. def __init__(self, title, link, description, language=None, author_email=None,
  49. author_name=None, author_link=None, subtitle=None, categories=None,
  50. feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs):
  51. def to_str(s):
  52. return str(s) if s is not None else s
  53. categories = categories and [str(c) for c in categories]
  54. self.feed = {
  55. 'title': to_str(title),
  56. 'link': iri_to_uri(link),
  57. 'description': to_str(description),
  58. 'language': to_str(language),
  59. 'author_email': to_str(author_email),
  60. 'author_name': to_str(author_name),
  61. 'author_link': iri_to_uri(author_link),
  62. 'subtitle': to_str(subtitle),
  63. 'categories': categories or (),
  64. 'feed_url': iri_to_uri(feed_url),
  65. 'feed_copyright': to_str(feed_copyright),
  66. 'id': feed_guid or link,
  67. 'ttl': to_str(ttl),
  68. **kwargs,
  69. }
  70. self.items = []
  71. def add_item(self, title, link, description, author_email=None,
  72. author_name=None, author_link=None, pubdate=None, comments=None,
  73. unique_id=None, unique_id_is_permalink=None, categories=(),
  74. item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs):
  75. """
  76. Add an item to the feed. All args are expected to be strings except
  77. pubdate and updateddate, which are datetime.datetime objects, and
  78. enclosures, which is an iterable of instances of the Enclosure class.
  79. """
  80. def to_str(s):
  81. return str(s) if s is not None else s
  82. categories = categories and [to_str(c) for c in categories]
  83. self.items.append({
  84. 'title': to_str(title),
  85. 'link': iri_to_uri(link),
  86. 'description': to_str(description),
  87. 'author_email': to_str(author_email),
  88. 'author_name': to_str(author_name),
  89. 'author_link': iri_to_uri(author_link),
  90. 'pubdate': pubdate,
  91. 'updateddate': updateddate,
  92. 'comments': to_str(comments),
  93. 'unique_id': to_str(unique_id),
  94. 'unique_id_is_permalink': unique_id_is_permalink,
  95. 'enclosures': enclosures or (),
  96. 'categories': categories or (),
  97. 'item_copyright': to_str(item_copyright),
  98. 'ttl': to_str(ttl),
  99. **kwargs,
  100. })
  101. def num_items(self):
  102. return len(self.items)
  103. def root_attributes(self):
  104. """
  105. Return extra attributes to place on the root (i.e. feed/channel) element.
  106. Called from write().
  107. """
  108. return {}
  109. def add_root_elements(self, handler):
  110. """
  111. Add elements in the root (i.e. feed/channel) element. Called
  112. from write().
  113. """
  114. pass
  115. def item_attributes(self, item):
  116. """
  117. Return extra attributes to place on each item (i.e. item/entry) element.
  118. """
  119. return {}
  120. def add_item_elements(self, handler, item):
  121. """
  122. Add elements on each item (i.e. item/entry) element.
  123. """
  124. pass
  125. def write(self, outfile, encoding):
  126. """
  127. Output the feed in the given encoding to outfile, which is a file-like
  128. object. Subclasses should override this.
  129. """
  130. raise NotImplementedError('subclasses of SyndicationFeed must provide a write() method')
  131. def writeString(self, encoding):
  132. """
  133. Return the feed in the given encoding as a string.
  134. """
  135. s = StringIO()
  136. self.write(s, encoding)
  137. return s.getvalue()
  138. def latest_post_date(self):
  139. """
  140. Return the latest item's pubdate or updateddate. If no items
  141. have either of these attributes this return the current UTC date/time.
  142. """
  143. latest_date = None
  144. date_keys = ('updateddate', 'pubdate')
  145. for item in self.items:
  146. for date_key in date_keys:
  147. item_date = item.get(date_key)
  148. if item_date:
  149. if latest_date is None or item_date > latest_date:
  150. latest_date = item_date
  151. # datetime.now(tz=utc) is slower, as documented in django.utils.timezone.now
  152. return latest_date or datetime.datetime.utcnow().replace(tzinfo=utc)
  153. class Enclosure:
  154. """An RSS enclosure"""
  155. def __init__(self, url, length, mime_type):
  156. "All args are expected to be strings"
  157. self.length, self.mime_type = length, mime_type
  158. self.url = iri_to_uri(url)
  159. class RssFeed(SyndicationFeed):
  160. content_type = 'application/rss+xml; charset=utf-8'
  161. def write(self, outfile, encoding):
  162. handler = SimplerXMLGenerator(outfile, encoding)
  163. handler.startDocument()
  164. handler.startElement("rss", self.rss_attributes())
  165. handler.startElement("channel", self.root_attributes())
  166. self.add_root_elements(handler)
  167. self.write_items(handler)
  168. self.endChannelElement(handler)
  169. handler.endElement("rss")
  170. def rss_attributes(self):
  171. return {
  172. 'version': self._version,
  173. 'xmlns:atom': 'http://www.w3.org/2005/Atom',
  174. }
  175. def write_items(self, handler):
  176. for item in self.items:
  177. handler.startElement('item', self.item_attributes(item))
  178. self.add_item_elements(handler, item)
  179. handler.endElement("item")
  180. def add_root_elements(self, handler):
  181. handler.addQuickElement("title", self.feed['title'])
  182. handler.addQuickElement("link", self.feed['link'])
  183. handler.addQuickElement("description", self.feed['description'])
  184. if self.feed['feed_url'] is not None:
  185. handler.addQuickElement("atom:link", None, {"rel": "self", "href": self.feed['feed_url']})
  186. if self.feed['language'] is not None:
  187. handler.addQuickElement("language", self.feed['language'])
  188. for cat in self.feed['categories']:
  189. handler.addQuickElement("category", cat)
  190. if self.feed['feed_copyright'] is not None:
  191. handler.addQuickElement("copyright", self.feed['feed_copyright'])
  192. handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date()))
  193. if self.feed['ttl'] is not None:
  194. handler.addQuickElement("ttl", self.feed['ttl'])
  195. def endChannelElement(self, handler):
  196. handler.endElement("channel")
  197. class RssUserland091Feed(RssFeed):
  198. _version = "0.91"
  199. def add_item_elements(self, handler, item):
  200. handler.addQuickElement("title", item['title'])
  201. handler.addQuickElement("link", item['link'])
  202. if item['description'] is not None:
  203. handler.addQuickElement("description", item['description'])
  204. class Rss201rev2Feed(RssFeed):
  205. # Spec: https://cyber.harvard.edu/rss/rss.html
  206. _version = "2.0"
  207. def add_item_elements(self, handler, item):
  208. handler.addQuickElement("title", item['title'])
  209. handler.addQuickElement("link", item['link'])
  210. if item['description'] is not None:
  211. handler.addQuickElement("description", item['description'])
  212. # Author information.
  213. if item["author_name"] and item["author_email"]:
  214. handler.addQuickElement("author", "%s (%s)" % (item['author_email'], item['author_name']))
  215. elif item["author_email"]:
  216. handler.addQuickElement("author", item["author_email"])
  217. elif item["author_name"]:
  218. handler.addQuickElement(
  219. "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"}
  220. )
  221. if item['pubdate'] is not None:
  222. handler.addQuickElement("pubDate", rfc2822_date(item['pubdate']))
  223. if item['comments'] is not None:
  224. handler.addQuickElement("comments", item['comments'])
  225. if item['unique_id'] is not None:
  226. guid_attrs = {}
  227. if isinstance(item.get('unique_id_is_permalink'), bool):
  228. guid_attrs['isPermaLink'] = str(item['unique_id_is_permalink']).lower()
  229. handler.addQuickElement("guid", item['unique_id'], guid_attrs)
  230. if item['ttl'] is not None:
  231. handler.addQuickElement("ttl", item['ttl'])
  232. # Enclosure.
  233. if item['enclosures']:
  234. enclosures = list(item['enclosures'])
  235. if len(enclosures) > 1:
  236. raise ValueError(
  237. "RSS feed items may only have one enclosure, see "
  238. "http://www.rssboard.org/rss-profile#element-channel-item-enclosure"
  239. )
  240. enclosure = enclosures[0]
  241. handler.addQuickElement('enclosure', '', {
  242. 'url': enclosure.url,
  243. 'length': enclosure.length,
  244. 'type': enclosure.mime_type,
  245. })
  246. # Categories.
  247. for cat in item['categories']:
  248. handler.addQuickElement("category", cat)
  249. class Atom1Feed(SyndicationFeed):
  250. # Spec: https://tools.ietf.org/html/rfc4287
  251. content_type = 'application/atom+xml; charset=utf-8'
  252. ns = "http://www.w3.org/2005/Atom"
  253. def write(self, outfile, encoding):
  254. handler = SimplerXMLGenerator(outfile, encoding)
  255. handler.startDocument()
  256. handler.startElement('feed', self.root_attributes())
  257. self.add_root_elements(handler)
  258. self.write_items(handler)
  259. handler.endElement("feed")
  260. def root_attributes(self):
  261. if self.feed['language'] is not None:
  262. return {"xmlns": self.ns, "xml:lang": self.feed['language']}
  263. else:
  264. return {"xmlns": self.ns}
  265. def add_root_elements(self, handler):
  266. handler.addQuickElement("title", self.feed['title'])
  267. handler.addQuickElement("link", "", {"rel": "alternate", "href": self.feed['link']})
  268. if self.feed['feed_url'] is not None:
  269. handler.addQuickElement("link", "", {"rel": "self", "href": self.feed['feed_url']})
  270. handler.addQuickElement("id", self.feed['id'])
  271. handler.addQuickElement("updated", rfc3339_date(self.latest_post_date()))
  272. if self.feed['author_name'] is not None:
  273. handler.startElement("author", {})
  274. handler.addQuickElement("name", self.feed['author_name'])
  275. if self.feed['author_email'] is not None:
  276. handler.addQuickElement("email", self.feed['author_email'])
  277. if self.feed['author_link'] is not None:
  278. handler.addQuickElement("uri", self.feed['author_link'])
  279. handler.endElement("author")
  280. if self.feed['subtitle'] is not None:
  281. handler.addQuickElement("subtitle", self.feed['subtitle'])
  282. for cat in self.feed['categories']:
  283. handler.addQuickElement("category", "", {"term": cat})
  284. if self.feed['feed_copyright'] is not None:
  285. handler.addQuickElement("rights", self.feed['feed_copyright'])
  286. def write_items(self, handler):
  287. for item in self.items:
  288. handler.startElement("entry", self.item_attributes(item))
  289. self.add_item_elements(handler, item)
  290. handler.endElement("entry")
  291. def add_item_elements(self, handler, item):
  292. handler.addQuickElement("title", item['title'])
  293. handler.addQuickElement("link", "", {"href": item['link'], "rel": "alternate"})
  294. if item['pubdate'] is not None:
  295. handler.addQuickElement('published', rfc3339_date(item['pubdate']))
  296. if item['updateddate'] is not None:
  297. handler.addQuickElement('updated', rfc3339_date(item['updateddate']))
  298. # Author information.
  299. if item['author_name'] is not None:
  300. handler.startElement("author", {})
  301. handler.addQuickElement("name", item['author_name'])
  302. if item['author_email'] is not None:
  303. handler.addQuickElement("email", item['author_email'])
  304. if item['author_link'] is not None:
  305. handler.addQuickElement("uri", item['author_link'])
  306. handler.endElement("author")
  307. # Unique ID.
  308. if item['unique_id'] is not None:
  309. unique_id = item['unique_id']
  310. else:
  311. unique_id = get_tag_uri(item['link'], item['pubdate'])
  312. handler.addQuickElement("id", unique_id)
  313. # Summary.
  314. if item['description'] is not None:
  315. handler.addQuickElement("summary", item['description'], {"type": "html"})
  316. # Enclosures.
  317. for enclosure in item['enclosures']:
  318. handler.addQuickElement('link', '', {
  319. 'rel': 'enclosure',
  320. 'href': enclosure.url,
  321. 'length': enclosure.length,
  322. 'type': enclosure.mime_type,
  323. })
  324. # Categories.
  325. for cat in item['categories']:
  326. handler.addQuickElement("category", "", {"term": cat})
  327. # Rights.
  328. if item['item_copyright'] is not None:
  329. handler.addQuickElement("rights", item['item_copyright'])
  330. # This isolates the decision of what the system default is, so calling code can
  331. # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed".
  332. DefaultFeed = Rss201rev2Feed