Development of an internal social media platform with personalised dashboards for students
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

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