diff --git a/main.py b/main.py index 8549fc2..b2d8d80 100644 --- a/main.py +++ b/main.py @@ -36,6 +36,13 @@ def error(message): return jsonify({"error": message}) +def edges_to_json(edges): + return_list = [] + for e in edges: + return_list.append({"start":e[0],"end":e[1],"weight":edges[e]}) + return return_list + + @app.route('/api/nodes', methods=['GET']) def get_nodes(): return jsonify({'nodes': graph.nodes}) @@ -43,7 +50,7 @@ def get_nodes(): @app.route('/api/edges', methods=['GET']) def get_edges(): - return jsonify({'edges': graph.edges}) + return jsonify({'edges': edges_to_json(graph.edges)}) @app.route('/api/nodes', methods=['POST']) @@ -77,6 +84,10 @@ def create_edge(): start = request.json['start'] end = request.json['end'] weight = request.json['weight'] + try: + weight = float(weight) + except ValueError: + return error("Weight must be a number."), 400 if weight < 0: return error("Weight must be positive."), 400 if start == end: @@ -86,13 +97,9 @@ def create_edge(): if end not in graph.nodes: return error("End node does not exist."), 400 if (start,end) in graph.edges or (end,start) in graph.edges: - return error("Edge exists already."), 400 - try: - weight = float(weight) - except ValueError: - return error("Weight must be a number."), 400 + return error("Edge already exists."), 400 - edge = {(start,end): weight} + edge = {"start":start,"end":end, "weight": weight} graph.edges[(start,end)] = weight return jsonify(edge), 201 @@ -100,7 +107,7 @@ def create_edge(): @app.route("/") def index(): - return render_template("index.html", nodes=graph.nodes, edges=graph.edges) + return render_template("index.html", nodes=graph.nodes, edges=edges_to_json(graph.edges)) if __name__ == '__main__':