Share Pastebin
Guest
Public paste!

Tim Davies

By: a guest | Dec 7th, 2009 | Syntax: None | Size: 5.51 KB | Hits: 534 | Expires: Never
This paste has a previous version, view the difference. Copy text to clipboard
  1. #!/usr/bin/python
  2.  
  3. """
  4. GivesMeHope API  v1.0a
  5.  
  6. A Python implementation of the givesmehope.com API, which can be found here: http://www.givesmehope.com/apidoc.php
  7. Released under the GPL (GNU Public License) - http://www.gnu.org/licenses/gpl-3.0.txt
  8. Written by Tim Davies (a.k.a. Dotty)   - Nothing to do with GivesMeHope - I'm just a random Python coder :)
  9. Email/Bug reports to:  timdavies3@gmail.com
  10. Dedicated to Becca, who is awesome in every single way. <3
  11.  
  12.  
  13. This aims to be a simple module for writing scripts that tie-in with GivesMeHope.com.
  14. Example of use:
  15.  
  16.  import givesmehope
  17.  
  18.  api = givesmehope.API()
  19.  gmh = gmh.random_gmh()
  20.  item = gmh.getnextitem()
  21.  print item.title()+"\\n"+item.text()
  22.  
  23. This would fetch a random 'GivesMeHope' from the website and display it, along with the title.
  24.  
  25. A simple way to iterate over a number of items is like so:
  26.  
  27.  item = gmh.getnextitem()
  28.  while item != None:
  29.          print item.text()+"\\n\\n"  // or whatever you want to do.
  30.          item = gmh.getnextitem()
  31. """
  32.  
  33. __author__ = "Tim Davies"
  34. __license__ = "GPL"
  35. __version__ = "1.0a"
  36.  
  37. __maintainer__ = "Tim Davies"
  38. __email__ = "timdavies3@gmail.com"
  39. __status__ = "First Release, Incomplete but working"
  40.  
  41.  
  42. from xml.dom import minidom
  43. import urllib2
  44.  
  45. class Item:
  46.         """A class to hold a particular GivesMeHope and associated data, for example, title, author, comments, date, etc."""
  47.         def __init__(self, xml):
  48.                 """Initialise and parse XML."""
  49.                 self._xml = xml
  50.                 self._item_id = self._xml.attributes['id'].nodeValue
  51.                 self._author = self._xml.getElementsByTagName("author")[0].firstChild.nodeValue
  52.                 self._category = self._xml.getElementsByTagName("category")[0].firstChild.nodeValue
  53.                 self._yes = self._xml.getElementsByTagName("yes")[0].firstChild.nodeValue
  54.                 self._no = self._xml.getElementsByTagName("no")[0].firstChild.nodeValue
  55.                 self._numcomments = self._xml.getElementsByTagName("comments")[0].firstChild.nodeValue
  56.                 self._text = self._xml.getElementsByTagName("text")[0].firstChild.nodeValue
  57.                 self._commentsflag = self._xml.getElementsByTagName("comments_flag")[0].firstChild.nodeValue
  58.                 self._date = self._xml.getElementsByTagName("date")[0].firstChild.nodeValue
  59.         def __str__(self):
  60.                 return self._text
  61.         def id(self):
  62.                 """Get item ID."""
  63.                 return self._item_id
  64.         def author(self):
  65.                 return self._author
  66.         def category(self):
  67.                 return self._category
  68.         def date(self):
  69.                 return self._date
  70.         def yes(self):
  71.                 return self._yes
  72.         def no(self):
  73.                 return self._no
  74.         def numcomments(self):
  75.                 return self._numcomments
  76.         def text(self):
  77.                 return self._text.replace("&quot;", "'")
  78.         def commentsflag(self):
  79.                 return self._commentsflag
  80.  
  81. class GMH:
  82.         """The class provided by a request. Holds the XML for the entire page, not just the individual bits of text, comments, etc.
  83.         You should use GMH.getnextitem() to retrieve the class (of type Item) for an individual GMH (including comments, etc)."""
  84.         def __init__(self, rawdata):
  85.                 """Initialise and parse XML."""
  86.                 self.xmldoc = minidom.parseString(rawdata)
  87.                
  88.                 self.current_item = 0
  89.                
  90.                 self.language = str(self.xmldoc.getElementsByTagName("language")[0].firstChild.nodeValue)
  91.                 self.pubdate = str(self.xmldoc.getElementsByTagName("pubdate")[0].firstChild.nodeValue)
  92.                 self.errorcode = str(self.xmldoc.getElementsByTagName("code")[0].firstChild.nodeValue)
  93.                 if self.geterrorcode == 0:
  94.                         self.errors = None
  95.                 else:
  96.                         errors = self.xmldoc.getElementsByTagName("errors")
  97.                         errors = self.xmldoc.getElementsByTagName("error")
  98.                         foo = []
  99.                         for i in range(0, len(errors)):
  100.                                 foo.append(str(errors[i].firstChild.nodeValue))
  101.                         self.errors = foo
  102.                 self.activekey = str(self.xmldoc.getElementsByTagName("active_key")[0].firstChild.nodeValue)
  103.                
  104.                 self.items = []
  105.                 for i in range(0, self.getnumitems()):
  106.                         self.items.append(Item(self.xmldoc.getElementsByTagName("item")[i]))
  107.        
  108.         def __str__(self):
  109.                 """Returns the raw XML."""
  110.                 return self.xmldoc.toxml()
  111.        
  112.         def getlanguage(self):
  113.                 """Returns the value of the language tags"""
  114.                 return self.language
  115.                
  116.         def getpubdate(self):
  117.                 """Returns the date on which the item was published."""
  118.                 return self.pubdate
  119.        
  120.         def geterrorcode(self):
  121.                 """Returns the value of the request. 0 means there was a massive error."""
  122.                 return self.errorcode
  123.        
  124.         def geterrors(self):
  125.                 """Returns list of errors. There always seems to be an API key problem, not sure why."""
  126.                 return self.errors
  127.        
  128.         def getactivekey(self):
  129.                 """No idea what this is for, but was part of the API so added in."""
  130.                 return self.activekey
  131.        
  132.         def getnumitems(self):
  133.                 """Return number of 'items', i.e. GMHs."""
  134.                 return self.xmldoc.getElementsByTagName("item").length
  135.        
  136.         def getnextitem(self):
  137.                 """Gets the next 'item', i.e. GMH. Returns an 'item' class."""
  138.                 try:
  139.                         return_value = self.items[self.current_item]
  140.                 except:
  141.                         return None
  142.                 self.current_item += 1
  143.                 return return_value
  144.        
  145.         def getnumcomments(self):
  146.                 """Return number of comments."""
  147.                 return self.xmldoc.getElementsByTagName("comments").length
  148.  
  149. class API:
  150.         """Class to hold the API functions - the first class to be used. For example, API.random_gmh() returns a random GMH (of class GMH).
  151.         Also to be used for logging in, posting new GMHs etc."""
  152.  
  153.         def random_gmh(self):
  154.                 """Uses the API to choose a random GMH. (GET /view/random)"""
  155.                 return GMH(urllib2.urlopen("http://api.givesmehope.com/view/random").read())
  156.        
  157.         def get_top(self, page=1):
  158.                 """Uses the API to return the top 15 GMHs. (GET /view/top)"""
  159.                 return GMH(urllib2.urlopen("http://api.givesmehope.com/view/top/"+str(page)).read())