import datetime import os import random from flask import Flask, abort, jsonify, request, redirect # An Episode is constructed as such: # data Episode = Episode # { name :: String # , air_date :: Int # , season :: Int # , episode :: Int # , is_movie :: Bool # } # # Any instance of season 99 should be interpreted as a movie. episodes = [] # First, open the input file and read in episodes with open("./fim.list", "r") as f: for line in f: airdate, s, e, name = line.split(' ', 4)[1:] episode = { "name": name[:-1], "air_date": int(airdate), "season": int(s), "episode": int(e), "is_movie": s == "99" } episodes.append(episode) # Now, initialize Flask app = Flask(__name__) @app.route("/") def hello(): return redirect("https://github.com/Xe/PonyAPI#ponyapi", code=302) @app.route("/all") def all_episodes(): return jsonify(episodes=episodes) @app.route("/newest") def newest_episode(): now = datetime.datetime(2006, 1, 4) now = now.now() for episode in episodes: if now.fromtimestamp(episode["air_date"]) > now: return jsonify(episode=episode) abort(500) @app.route("/season/") def season(number): retEpisodes = [] for episode in episodes: if str(episode["season"]) == number: retEpisodes.append(episode) try: assert len(retEpisodes) > 0 except: abort(404) return jsonify(episodes=retEpisodes) @app.route("/season//episode/") def show_episode(snumber, epnumber): for episode in episodes: if str(episode["season"]) == snumber and str(episode["episode"]) == epnumber: return jsonify(episode=episode) abort(404) @app.route("/random") def show_random_ep(): return jsonify(episode=random.choice(episodes)) @app.route("/search") def search(): retEpisodes = [] term = request.args.get("q", "").lower() try: assert term != "" except: abort(406) for episode in episodes: if term in episode["name"].lower(): retEpisodes.append(episode) try: assert len(retEpisodes) > 0 except: abort(404) return jsonify(episodes=retEpisodes) if __name__ == '__main__': app.run(host="0.0.0.0", debug=True)