feedgenerator.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 blog by the sharpest minds in online journalism.",
  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. import mimetypes
  24. from io import StringIO
  25. from urllib.parse import urlparse
  26. from django.forms.utils import flatatt
  27. from django.utils.encoding import iri_to_uri
  28. from django.utils.xmlutils import SimplerXMLGenerator
  29. def rfc2822_date(date):
  30. if not isinstance(date, datetime.datetime):
  31. date = datetime.datetime.combine(date, datetime.time())
  32. return email.utils.format_datetime(date)
  33. def rfc3339_date(date):
  34. if not isinstance(date, datetime.datetime):
  35. date = datetime.datetime.combine(date, datetime.time())
  36. return date.isoformat() + ("Z" if date.utcoffset() is None else "")
  37. def get_tag_uri(url, date):
  38. """
  39. Create a TagURI.
  40. See
  41. https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id
  42. """
  43. bits = urlparse(url)
  44. d = ""
  45. if date is not None:
  46. d = ",%s" % date.strftime("%Y-%m-%d")
  47. return "tag:%s%s:%s/%s" % (bits.hostname, d, bits.path, bits.fragment)
  48. def _guess_stylesheet_mimetype(url):
  49. """
  50. Return the given stylesheet's mimetype tuple, using a slightly custom
  51. version of Python's mimetypes.guess_type().
  52. """
  53. mimetypedb = mimetypes.MimeTypes()
  54. # The official mimetype for XSLT files is technically
  55. # `application/xslt+xml` but as of 2024 almost no browser supports that
  56. # (they all expect text/xsl). On top of that, windows seems to assume that
  57. # the type for xsl is text/xml.
  58. mimetypedb.readfp(StringIO("text/xsl\txsl\ntext/xsl\txslt"))
  59. return mimetypedb.guess_type(url)
  60. class Stylesheet:
  61. """An RSS stylesheet"""
  62. def __init__(self, url, mimetype="", media="screen"):
  63. self._url = url
  64. self._mimetype = mimetype
  65. self.media = media
  66. # Using a property to delay the evaluation of self._url as late as possible
  67. # in case of a lazy object (like reverse_lazy(...) for example).
  68. @property
  69. def url(self):
  70. return iri_to_uri(self._url)
  71. @property
  72. def mimetype(self):
  73. if self._mimetype == "":
  74. return _guess_stylesheet_mimetype(self.url)[0]
  75. return self._mimetype
  76. def __str__(self):
  77. attrs = {
  78. "href": iri_to_uri(self._url),
  79. "type": self.mimetype,
  80. "media": self.media,
  81. }
  82. return flatatt(attrs).strip()
  83. def __repr__(self):
  84. return repr((self.url, self.mimetype, self.media))
  85. class SyndicationFeed:
  86. "Base class for all syndication feeds. Subclasses should provide write()"
  87. def __init__(
  88. self,
  89. title,
  90. link,
  91. description,
  92. language=None,
  93. author_email=None,
  94. author_name=None,
  95. author_link=None,
  96. subtitle=None,
  97. categories=None,
  98. feed_url=None,
  99. feed_copyright=None,
  100. feed_guid=None,
  101. ttl=None,
  102. stylesheets=None,
  103. **kwargs,
  104. ):
  105. def to_str(s):
  106. return str(s) if s is not None else s
  107. def to_stylesheet(s):
  108. return s if isinstance(s, Stylesheet) else Stylesheet(s)
  109. categories = categories and [str(c) for c in categories]
  110. if stylesheets is not None:
  111. if isinstance(stylesheets, (Stylesheet, str)):
  112. raise TypeError(
  113. f"stylesheets should be a list, not {stylesheets.__class__}"
  114. )
  115. stylesheets = [to_stylesheet(s) for s in stylesheets]
  116. self.feed = {
  117. "title": to_str(title),
  118. "link": iri_to_uri(link),
  119. "description": to_str(description),
  120. "language": to_str(language),
  121. "author_email": to_str(author_email),
  122. "author_name": to_str(author_name),
  123. "author_link": iri_to_uri(author_link),
  124. "subtitle": to_str(subtitle),
  125. "categories": categories or (),
  126. "feed_url": iri_to_uri(feed_url),
  127. "feed_copyright": to_str(feed_copyright),
  128. "id": feed_guid or link,
  129. "ttl": to_str(ttl),
  130. "stylesheets": stylesheets,
  131. **kwargs,
  132. }
  133. self.items = []
  134. def add_item(
  135. self,
  136. title,
  137. link,
  138. description,
  139. author_email=None,
  140. author_name=None,
  141. author_link=None,
  142. pubdate=None,
  143. comments=None,
  144. unique_id=None,
  145. unique_id_is_permalink=None,
  146. categories=(),
  147. item_copyright=None,
  148. ttl=None,
  149. updateddate=None,
  150. enclosures=None,
  151. **kwargs,
  152. ):
  153. """
  154. Add an item to the feed. All args are expected to be strings except
  155. pubdate and updateddate, which are datetime.datetime objects, and
  156. enclosures, which is an iterable of instances of the Enclosure class.
  157. """
  158. def to_str(s):
  159. return str(s) if s is not None else s
  160. categories = categories and [to_str(c) for c in categories]
  161. self.items.append(
  162. {
  163. "title": to_str(title),
  164. "link": iri_to_uri(link),
  165. "description": to_str(description),
  166. "author_email": to_str(author_email),
  167. "author_name": to_str(author_name),
  168. "author_link": iri_to_uri(author_link),
  169. "pubdate": pubdate,
  170. "updateddate": updateddate,
  171. "comments": to_str(comments),
  172. "unique_id": to_str(unique_id),
  173. "unique_id_is_permalink": unique_id_is_permalink,
  174. "enclosures": enclosures or (),
  175. "categories": categories or (),
  176. "item_copyright": to_str(item_copyright),
  177. "ttl": to_str(ttl),
  178. **kwargs,
  179. }
  180. )
  181. def num_items(self):
  182. return len(self.items)
  183. def root_attributes(self):
  184. """
  185. Return extra attributes to place on the root (i.e. feed/channel)
  186. element. Called from write().
  187. """
  188. return {}
  189. def add_root_elements(self, handler):
  190. """
  191. Add elements in the root (i.e. feed/channel) element. Called
  192. from write().
  193. """
  194. pass
  195. def add_stylesheets(self, handler):
  196. """
  197. Add stylesheet(s) to the feed. Called from write().
  198. """
  199. pass
  200. def item_attributes(self, item):
  201. """
  202. Return extra attributes to place on each item (i.e. item/entry)
  203. element.
  204. """
  205. return {}
  206. def add_item_elements(self, handler, item):
  207. """
  208. Add elements on each item (i.e. item/entry) element.
  209. """
  210. pass
  211. def write(self, outfile, encoding):
  212. """
  213. Output the feed in the given encoding to outfile, which is a file-like
  214. object. Subclasses should override this.
  215. """
  216. raise NotImplementedError(
  217. "subclasses of SyndicationFeed must provide a write() method"
  218. )
  219. def writeString(self, encoding):
  220. """
  221. Return the feed in the given encoding as a string.
  222. """
  223. s = StringIO()
  224. self.write(s, encoding)
  225. return s.getvalue()
  226. def latest_post_date(self):
  227. """
  228. Return the latest item's pubdate or updateddate. If no items
  229. have either of these attributes this return the current UTC date/time.
  230. """
  231. latest_date = None
  232. date_keys = ("updateddate", "pubdate")
  233. for item in self.items:
  234. for date_key in date_keys:
  235. item_date = item.get(date_key)
  236. if item_date:
  237. if latest_date is None or item_date > latest_date:
  238. latest_date = item_date
  239. return latest_date or datetime.datetime.now(tz=datetime.UTC)
  240. class Enclosure:
  241. """An RSS enclosure"""
  242. def __init__(self, url, length, mime_type):
  243. "All args are expected to be strings"
  244. self.length, self.mime_type = length, mime_type
  245. self.url = iri_to_uri(url)
  246. class RssFeed(SyndicationFeed):
  247. content_type = "application/rss+xml; charset=utf-8"
  248. def write(self, outfile, encoding):
  249. handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True)
  250. handler.startDocument()
  251. # Any stylesheet must come after the start of the document but before
  252. # any tag. https://www.w3.org/Style/styling-XML.en.html
  253. self.add_stylesheets(handler)
  254. handler.startElement("rss", self.rss_attributes())
  255. handler.startElement("channel", self.root_attributes())
  256. self.add_root_elements(handler)
  257. self.write_items(handler)
  258. self.endChannelElement(handler)
  259. handler.endElement("rss")
  260. def rss_attributes(self):
  261. return {
  262. "version": self._version,
  263. "xmlns:atom": "http://www.w3.org/2005/Atom",
  264. }
  265. def write_items(self, handler):
  266. for item in self.items:
  267. handler.startElement("item", self.item_attributes(item))
  268. self.add_item_elements(handler, item)
  269. handler.endElement("item")
  270. def add_stylesheets(self, handler):
  271. for stylesheet in self.feed["stylesheets"] or []:
  272. handler.processingInstruction("xml-stylesheet", stylesheet)
  273. def add_root_elements(self, handler):
  274. handler.addQuickElement("title", self.feed["title"])
  275. handler.addQuickElement("link", self.feed["link"])
  276. handler.addQuickElement("description", self.feed["description"])
  277. if self.feed["feed_url"] is not None:
  278. handler.addQuickElement(
  279. "atom:link", None, {"rel": "self", "href": self.feed["feed_url"]}
  280. )
  281. if self.feed["language"] is not None:
  282. handler.addQuickElement("language", self.feed["language"])
  283. for cat in self.feed["categories"]:
  284. handler.addQuickElement("category", cat)
  285. if self.feed["feed_copyright"] is not None:
  286. handler.addQuickElement("copyright", self.feed["feed_copyright"])
  287. handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date()))
  288. if self.feed["ttl"] is not None:
  289. handler.addQuickElement("ttl", self.feed["ttl"])
  290. def endChannelElement(self, handler):
  291. handler.endElement("channel")
  292. class RssUserland091Feed(RssFeed):
  293. _version = "0.91"
  294. def add_item_elements(self, handler, item):
  295. handler.addQuickElement("title", item["title"])
  296. handler.addQuickElement("link", item["link"])
  297. if item["description"] is not None:
  298. handler.addQuickElement("description", item["description"])
  299. class Rss201rev2Feed(RssFeed):
  300. # Spec: https://cyber.harvard.edu/rss/rss.html
  301. _version = "2.0"
  302. def add_item_elements(self, handler, item):
  303. handler.addQuickElement("title", item["title"])
  304. handler.addQuickElement("link", item["link"])
  305. if item["description"] is not None:
  306. handler.addQuickElement("description", item["description"])
  307. # Author information.
  308. if item["author_name"] and item["author_email"]:
  309. handler.addQuickElement(
  310. "author", "%s (%s)" % (item["author_email"], item["author_name"])
  311. )
  312. elif item["author_email"]:
  313. handler.addQuickElement("author", item["author_email"])
  314. elif item["author_name"]:
  315. handler.addQuickElement(
  316. "dc:creator",
  317. item["author_name"],
  318. {"xmlns:dc": "http://purl.org/dc/elements/1.1/"},
  319. )
  320. if item["pubdate"] is not None:
  321. handler.addQuickElement("pubDate", rfc2822_date(item["pubdate"]))
  322. if item["comments"] is not None:
  323. handler.addQuickElement("comments", item["comments"])
  324. if item["unique_id"] is not None:
  325. guid_attrs = {}
  326. if isinstance(item.get("unique_id_is_permalink"), bool):
  327. guid_attrs["isPermaLink"] = str(item["unique_id_is_permalink"]).lower()
  328. handler.addQuickElement("guid", item["unique_id"], guid_attrs)
  329. if item["ttl"] is not None:
  330. handler.addQuickElement("ttl", item["ttl"])
  331. # Enclosure.
  332. if item["enclosures"]:
  333. enclosures = list(item["enclosures"])
  334. if len(enclosures) > 1:
  335. raise ValueError(
  336. "RSS feed items may only have one enclosure, see "
  337. "http://www.rssboard.org/rss-profile#element-channel-item-enclosure"
  338. )
  339. enclosure = enclosures[0]
  340. handler.addQuickElement(
  341. "enclosure",
  342. "",
  343. {
  344. "url": enclosure.url,
  345. "length": enclosure.length,
  346. "type": enclosure.mime_type,
  347. },
  348. )
  349. # Categories.
  350. for cat in item["categories"]:
  351. handler.addQuickElement("category", cat)
  352. class Atom1Feed(SyndicationFeed):
  353. # Spec: https://tools.ietf.org/html/rfc4287
  354. content_type = "application/atom+xml; charset=utf-8"
  355. ns = "http://www.w3.org/2005/Atom"
  356. def write(self, outfile, encoding):
  357. handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True)
  358. handler.startDocument()
  359. handler.startElement("feed", self.root_attributes())
  360. self.add_root_elements(handler)
  361. self.write_items(handler)
  362. handler.endElement("feed")
  363. def root_attributes(self):
  364. if self.feed["language"] is not None:
  365. return {"xmlns": self.ns, "xml:lang": self.feed["language"]}
  366. else:
  367. return {"xmlns": self.ns}
  368. def add_root_elements(self, handler):
  369. handler.addQuickElement("title", self.feed["title"])
  370. handler.addQuickElement(
  371. "link", "", {"rel": "alternate", "href": self.feed["link"]}
  372. )
  373. if self.feed["feed_url"] is not None:
  374. handler.addQuickElement(
  375. "link", "", {"rel": "self", "href": self.feed["feed_url"]}
  376. )
  377. handler.addQuickElement("id", self.feed["id"])
  378. handler.addQuickElement("updated", rfc3339_date(self.latest_post_date()))
  379. if self.feed["author_name"] is not None:
  380. handler.startElement("author", {})
  381. handler.addQuickElement("name", self.feed["author_name"])
  382. if self.feed["author_email"] is not None:
  383. handler.addQuickElement("email", self.feed["author_email"])
  384. if self.feed["author_link"] is not None:
  385. handler.addQuickElement("uri", self.feed["author_link"])
  386. handler.endElement("author")
  387. if self.feed["subtitle"] is not None:
  388. handler.addQuickElement("subtitle", self.feed["subtitle"])
  389. for cat in self.feed["categories"]:
  390. handler.addQuickElement("category", "", {"term": cat})
  391. if self.feed["feed_copyright"] is not None:
  392. handler.addQuickElement("rights", self.feed["feed_copyright"])
  393. def write_items(self, handler):
  394. for item in self.items:
  395. handler.startElement("entry", self.item_attributes(item))
  396. self.add_item_elements(handler, item)
  397. handler.endElement("entry")
  398. def add_item_elements(self, handler, item):
  399. handler.addQuickElement("title", item["title"])
  400. handler.addQuickElement("link", "", {"href": item["link"], "rel": "alternate"})
  401. if item["pubdate"] is not None:
  402. handler.addQuickElement("published", rfc3339_date(item["pubdate"]))
  403. if item["updateddate"] is not None:
  404. handler.addQuickElement("updated", rfc3339_date(item["updateddate"]))
  405. # Author information.
  406. if item["author_name"] is not None:
  407. handler.startElement("author", {})
  408. handler.addQuickElement("name", item["author_name"])
  409. if item["author_email"] is not None:
  410. handler.addQuickElement("email", item["author_email"])
  411. if item["author_link"] is not None:
  412. handler.addQuickElement("uri", item["author_link"])
  413. handler.endElement("author")
  414. # Unique ID.
  415. if item["unique_id"] is not None:
  416. unique_id = item["unique_id"]
  417. else:
  418. unique_id = get_tag_uri(item["link"], item["pubdate"])
  419. handler.addQuickElement("id", unique_id)
  420. # Summary.
  421. if item["description"] is not None:
  422. handler.addQuickElement("summary", item["description"], {"type": "html"})
  423. # Enclosures.
  424. for enclosure in item["enclosures"]:
  425. handler.addQuickElement(
  426. "link",
  427. "",
  428. {
  429. "rel": "enclosure",
  430. "href": enclosure.url,
  431. "length": enclosure.length,
  432. "type": enclosure.mime_type,
  433. },
  434. )
  435. # Categories.
  436. for cat in item["categories"]:
  437. handler.addQuickElement("category", "", {"term": cat})
  438. # Rights.
  439. if item["item_copyright"] is not None:
  440. handler.addQuickElement("rights", item["item_copyright"])
  441. # This isolates the decision of what the system default is, so calling code can
  442. # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed".
  443. DefaultFeed = Rss201rev2Feed