from flask import Flask, render_template, jsonify, Response, request import requests from flask_cors import CORS # configuration DEBUG = True # instantiate the app app = Flask(__name__) app.config.from_object(__name__) # enable CORS CORS(app, resources={r'/*': {'origins': '*'}}) # sanity check route @app.route('/ping', methods=['GET']) def ping_pong(): return jsonify('Pong!') # get list of items @app.route("/items", methods=['GET']) def getItems(): """ @return items:json """ # get latest item id maxId = requests.get("https://hacker-news.firebaseio.com/v0/maxitem.json") maxId = int(maxId.text) itemlist = [] for count in range(10): newdata = requests.get("https://hacker-news.firebaseio.com/v0/item/" + str(maxId) + ".json") # if any error occurrs, jump to next item if(newdata.status_code != 200): continue itemlist.append(newdata.text) maxId-=1 response_object = {'status': 200} response_object["items"] = itemlist return jsonify(response_object) @app.route("/items", methods=["POST"]) def getSpezialItems(): """ @param category:string @param count:integer @return items:json """ category = str(request.form["category"]) count = int(request.form["count"]) println(category) println(count) # get latest item id maxId = requests.get("https://hacker-news.firebaseio.com/v0/maxitem.json") maxId = int(maxId.text) itemlist = [] # get count amount of items of certain category counter = 0 if count <= 0 | count >= 50: count = 10 while counter < count: newdata = get("https://hacker-news.firebaseio.com/v0/item/" + str(maxId) + ".json") # if any error occurrs, jump to next item if(newdata.status_code != 200): continue # only if category matches it is pushed to the answer array for dict in newdata.text: if dict['category'] == category: itemlist.append(newdata.text) counter+=1 maxId-=1 response_object = {'status': 200} response_object["items"] = itemlist return jsonify(response_object) # get single item by id @app.route("/item/", methods=["GET"]) def getItem(itemId): """ @param itemId:integer @return item:json """ data = requests.get("https://hacker-news.firebaseio.com/v0/item/" + itemId + ".json") if(data.status_code != 200): return jsonify({ "status_code": 400, "error": "Currently there is a problem with the HackerNews API" }) else: response_object = {'status': 200} response_object["item"] = data.text return jsonify(response_object) # send single-page-app to client @app.route("/") def getIndex(): return render_template("index.html")