Skip to content

Instantly share code, notes, and snippets.

@jiphex
Created July 25, 2008 10:22
Show Gist options
  • Save jiphex/2419 to your computer and use it in GitHub Desktop.
Save jiphex/2419 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
import sys, os
import httplib # JSON Retrieval
import simplejson # JSON Parsing
class Story(object):
"""
Class to represent a single Reddit story.
- Stories in lists are sortable (__cmp__)
- Stories define a sensible unicode method.
"""
def __init__(self, title, score):
self.title = title
self.score = score
def __unicode__(self):
return self.title
def __cmp__(self, other):
return cmp(self.score, other.score)
class RedditGetter(object):
"""Class for retrieving stories from Reddit using the JSON API."""
REDDIT_ADDRESS = 'www.reddit.com'
@classmethod
def reddit_json_path(self, key):
"""
Returns the path to a specified reddit.
Example:
>>> import redditgetter
>>> redditgetter.RedditGetter.reddit_json_path('programming')
'/r/programming/.json'
"""
return "/r/%s/.json" % key
@classmethod
def get_stories(self, subreddit='reddit.com'):
"""Returns a list of Story objects from the specified subreddit."""
httpcon = httplib.HTTPConnection(self.REDDIT_ADDRESS)
httpcon.request("GET",
RedditGetter.reddit_json_path(subreddit),
headers={"Accept-Encoding": "text/x-json"})
jsondata = httpcon.getresponse().read()
reddit = map(lambda x: Story(x['data']['title'], x['data']['score']),
simplejson.loads(jsondata)['data']['children'])
return reddit
def main():
stories = RedditGetter.get_stories()
for story in stories:
print "%d\t%s" % (story.score, story.title)
if(__name__ == "__main__"):
if(len(sys.argv) > 2 and sys.argv[1] == 'test'):
import doctest
doctest.testmod()
else:
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment