# -*- coding: utf-8 -*- import pymysql M = dict( host='cq-cdb-8fjmemkb.sql.tencentcdb.com', port=27220, user='root', password='Ylrz_1q2w3e4r5t6y', database='ylrz_saas', charset='utf8mb4', ) def build_tree(rows, parent_id=0): tree = [] for r in rows: if r['parent_id'] == parent_id: node = dict(r) node['children'] = build_tree(rows, r['menu_id']) tree.append(node) tree.sort(key=lambda x: (x.get('order_num') or 0, x['menu_id'])) return tree def print_tree(nodes, depth=0, max_depth=2): for n in nodes: print(' ' * depth + '- %s (id=%s, path=%s)' % (n['menu_name'], n['menu_id'], n['path'])) if depth < max_depth and n.get('children'): print_tree(n['children'], depth + 1, max_depth) c = pymysql.connect(**M) cur = c.cursor(pymysql.cursors.DictCursor) cur.execute( "SELECT menu_id, menu_name, parent_id, order_num, path, menu_type, visible " "FROM tenant_sys_menu WHERE visible='0' ORDER BY parent_id, order_num, menu_id" ) rows = cur.fetchall() tree = build_tree(rows, 0) print('API visible=0 top level count:', len(tree)) print_tree(tree, 0, 2) cur.close() c.close()