Skip to content

Instantly share code, notes, and snippets.

@berinhard
Last active January 20, 2016 13:51
Show Gist options
  • Save berinhard/28074131f09497c5b452 to your computer and use it in GitHub Desktop.
Save berinhard/28074131f09497c5b452 to your computer and use it in GitHub Desktop.
Pyvideos.org Safe Box
# coding:utf-8
import requests
from collections import Iterator
def api_data_fetcher(url):
response = requests.get(url)
if not response.ok:
raise Exception(u'Request error: {}'.format(response.content))
return response.json()
class Resource(object):
@property
def data(self):
if not getattr(self, '_data', None):
self._data = api_data_fetcher(self.url)
return self._data
class Video(Resource):
def __init__(self, url):
self.url = url
class Category(object):
def __init__(self, data):
self.data = data
@property
def videos(self):
for url in self.data['videos']:
yield Video(url)
class Categories(Iterator, Resource):
def __init__(self, url):
self.url = url
self.__results = []
self.__current_category = None
def __iter__(self):
return self
def refresh(self, url):
self.url = url
self._data = {}
self.__results = []
self.__current_category = None
def next(self):
if not self.__current_category:
self.__results = list(self.data['results'])
elif not self.__results:
next_url = self.data['next']
if not next_url:
raise StopIteration
self.refresh(next_url)
return self.next()
self.__current_category = Category(self.__results.pop())
return self.__current_category
if __name__ == '__main__':
url = 'http://pyvideo.org/api/v2/category/'
for category in Categories(url):
print category.data['slug']
for video in category.videos:
print '\t' + video.data['slug']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment