from flask import Flask, render_template, g from flask.json import jsonify from flask.templating import render_template_string from sqlalchemy.orm import joinedload import ttdb from ttdb.model import HierarchyElement, obtain_session #configuration SQL_CONNECTION_STRING = "sqlite:///tt.db" DEBUG = True app = Flask(__name__) #app.config.from_object('config') app.config.from_object(__name__) @app.before_request def before_request(): g.ttdb = obtain_session(app.config["SQL_CONNECTION_STRING"]) @app.teardown_request def teardown_request(exception): #tdb = getattr(g, 'db', None) pass @app.errorhandler(404) def not_found(error): return render_template('404.html') @app.route('/') @app.route('/tree') def tree(): elements = g.ttdb.query(HierarchyElement).options(joinedload('children')).all() #root elements root_elements = [element for element in elements if element.parent_id is None] #render return render_template('tree.html', elements=root_elements) @app.route('/get_children/') def get_children(id): element = g.ttdb.query(HierarchyElement).get(id) return jsonify(children=element.children) @app.route('/table') def table(): #select all elements populating children right away elements = g.ttdb.query(HierarchyElement).options(joinedload('children', 'channel')).all() #root elements root_elements = [element for element in elements if element.parent_id is None] #recursive function to sort array according to hierarchy ordered_elements = [] def build_hierarchy(el, level): ordered_elements.append((" "*5*level, el,)) if len(el.children): for child in el.children: build_hierarchy(child, level+1) for root_element in root_elements: build_hierarchy(root_element, 0) #render return render_template('index.html', elements=ordered_elements)