Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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