将组织结构转换为树状json

2021-03-22 08:25

阅读:444

标签:pen   org   eve   orm   mit   append   highlight   pre   ret   

# -*-coding:utf8-*-
import pymysql
import datetime
import json
import random
import logging

logging.basicConfig(filename="test_convert_org_to_tree.log",filemode="a",
                    format="%(asctime)s-%(funcName)s-%(lineno)d-%(levelname)s:%(message)s",level=logging.INFO)
console = logging.StreamHandler()
logging.getLogger().addHandler(console)

def execute_sql(sqlstr):
	db = pymysql.connect("10.136.142.111","liumin1","liumin1","liumin1",port=3306 )
	cursor = db.cursor()
	try:
		cursor.execute(sqlstr)
		if(sqlstr.lower().startswith("select")):
			data = cursor.fetchall()
		db.commit()
	except Exception as e:
		logging.info(e)
		logging.info("执行失败的SQL是:%s" % sqlstr)
		db.rollback()
	db.close()
	try:
		return data 
	except Exception as e:
		return None

# def convert_table_to_org(data_list):
# 	org = {}
# 	org["id"] = data_list[0]
# 	org["name"] = data_list[1]
# 	org["parentid"] = data_list[2]
# 	return org

def consalt_table_to_python(sqlstr):
	logging.info("要执行的SQL是:%s" % sqlstr)
	data = execute_sql(sqlstr)
	# if(not data):
	# 	return
	org_list = []
	logging.info("data是:%s" % json.dumps(data))
	for i in data:
		org = {}
		org["id"] = i[0]
		org["name"] = i[1]
		org["parentid"] = i[2]
		org_list.append(org)

	return org_list 

def get_sub_children(org_tree):
	sqlstr = "select id,name,parentid from liuyue_test_org where parentid=%d;" %org_tree["id"]
	org_tree_tmp = consalt_table_to_python(sqlstr)
	logging.info("org_tree_tmp是:%s" % org_tree_tmp)
	# if(org_tree_tmp):
	for i in org_tree_tmp:
		logging.info("i是:%s" % i)
		get_sub_children(i)
	org_tree["childrenlist"]=org_tree_tmp

def convert_org_to_tree():
	sqlstr = "select id,name,parentid from liuyue_test_org where parentid=0;"
	org_tree = consalt_table_to_python(sqlstr)[0]
	get_sub_children(org_tree)
	return (json.dumps(org_tree))

print(convert_org_to_tree())

  

将组织结构转换为树状json

标签:pen   org   eve   orm   mit   append   highlight   pre   ret   

原文地址:https://www.cnblogs.com/yahutiaotiao/p/12708348.html


评论


亲,登录后才可以留言!