ponyapi/client/python/ponyapi.py

99 lines
2.5 KiB
Python
Raw Normal View History

2015-08-09 21:34:29 +00:00
import requests
import time
2015-08-09 21:34:29 +00:00
"""
# PonyAPI module for Python programs
This is written in a metaprogramming style.
Usage:
```python
import ponyapi
episodes = ponyapi.all_episodes()
for episode in episodes:
print episode
```
Available methods:
all_episodes() -> return all information on all episodes
newest() -> return information on the newest episode
last_aired() -> returns the episode that most recently aired
2015-08-09 21:34:29 +00:00
random() -> return a random episode
get_season(snum) -> return all episodes in season snum
get_episode(snum, enum) -> return info on season snum episode enum
search(query) -> return all episodes that have query in the title
"""
2016-01-16 16:15:54 +00:00
API_ENDPOINT = "https://ponyapi.apps.xeserv.us"
2015-08-09 21:34:29 +00:00
2015-08-09 21:44:06 +00:00
# _base_get :: Text -> Maybe [Text] -> (Maybe [Text] -> IO (Either Episode [Episode]))
# _base_get takes a text, a splatted list of texts and returns a function such that
# the function takes a splatted list of texts and returns either an Episode or
# a list of Episode as an IO action.
2015-08-09 21:34:29 +00:00
def _base_get(endpoint, *fragments):
def doer(*args):
r = None
assert len(fragments) == len(args)
if len(fragments) == 0:
r = requests.get(API_ENDPOINT + endpoint)
else:
url = API_ENDPOINT + endpoint
for i in range(len(fragments)):
url = url + "/" + fragments[i] + "/" + str(args[i])
r = requests.get(url)
if r.status_code != 200:
raise Exception("Not found or server error")
2015-08-09 22:59:57 +00:00
try:
return r.json()["episodes"]
except:
return r.json()["episode"]
2015-08-09 21:34:29 +00:00
return doer
# all_episodes :: IO [Episode]
all_episodes = _base_get("/all")
# newest :: IO Episode
newest = _base_get("/newest")
2015-08-17 21:36:41 +00:00
# last_aired :: IO Episode
last_aired = _base_get("/last_aired")
2015-08-09 21:34:29 +00:00
# random :: IO Episode
random = _base_get("/random")
# get_season :: Int -> IO [Episode]
get_season = _base_get("", "season")
# get_episode :: Int -> Int -> IO Episode
get_episode = _base_get("", "season", "episode")
2015-08-09 21:41:19 +00:00
# search :: Text -> IO [Episode]
2015-08-09 21:34:29 +00:00
def search(query):
params = {"q": query}
r = requests.get(API_ENDPOINT + "/search", params=params)
if r.status_code != 200:
raise Exception("Not found or server error")
2015-08-09 22:59:57 +00:00
return r.json()["episodes"]
2015-08-17 21:36:41 +00:00
# last_aired_old :: IO Episode
# TODO: Does not know how to wrap around seasons, fix this
2015-08-17 21:36:41 +00:00
def last_aired_old():
new = newest()
if new[u"air_date"] > int(time.time()):
return get_episode(new[u"season"], (new[u"episode"]-1))
return new