提交 1c3c5409e8375863a24b6eb4bdceb029e809b459

作者 nheweijun
1 个父辈 9bd0f41a

change

要显示太多修改。

为保证性能只显示 31 of 92 个文件。

@@ -128,7 +128,7 @@ def data_entry_center(): @@ -128,7 +128,7 @@ def data_entry_center():
128 128
129 if inter_size < configure.entry_data_thread: 129 if inter_size < configure.entry_data_thread:
130 # 锁表啊 130 # 锁表啊
131 - ready_task:Task = sys_session.query(Task).filter_by(state=0).order_by(Task.create_time).with_lockmode("update").limit(1).one_or_none() 131 + ready_task:Task = sys_session.query(Task).filter_by(state=0,task_type=1).order_by(Task.create_time).with_lockmode("update").limit(1).one_or_none()
132 if ready_task: 132 if ready_task:
133 133
134 try: 134 try:
@@ -72,6 +72,8 @@ class Table(db.Model): @@ -72,6 +72,8 @@ class Table(db.Model):
72 72
73 #用户 73 #用户
74 creator = Column(Text) 74 creator = Column(Text)
  75 + #是否已抽稀
  76 + is_vacuate=Column(Integer,default=0)
75 77
76 # 目录外键 78 # 目录外键
77 catalog_guid = Column(String(256), ForeignKey('dmdms_catalog.guid')) 79 catalog_guid = Column(String(256), ForeignKey('dmdms_catalog.guid'))
@@ -122,6 +124,10 @@ class Task(db.Model): @@ -122,6 +124,10 @@ class Task(db.Model):
122 # 目录外键 124 # 目录外键
123 catalog_guid = Column(String(256), ForeignKey('dmdms_catalog.guid')) 125 catalog_guid = Column(String(256), ForeignKey('dmdms_catalog.guid'))
124 126
  127 + table_guid = Column(String(256))
  128 + #任务类型
  129 + task_type=Column(Integer)
  130 +
125 creator = Column(Text) 131 creator = Column(Text)
126 file_name = Column(Text) 132 file_name = Column(Text)
127 133
1 -# coding=utf-8  
2 -# author: 4N  
3 -# createtime: 2020/8/27  
4 -# email: nheweijun@sina.com 1 +# coding=utf-8
  2 +# author: 4N
  3 +# createtime: 2020/8/27
  4 +# email: nheweijun@sina.com
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/1  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from flasgger import swag_from  
8 -from flask import Blueprint  
9 -from app.util import BlueprintApi  
10 -from . import catalog_create  
11 -from . import catalog_next  
12 -from . import catalog_tree  
13 -from . import catalog_delete  
14 -from . import catalog_edit  
15 -from . import catalog_real_tree  
16 -  
17 -  
18 -class DataManager(BlueprintApi):  
19 -  
20 - bp = Blueprint("Category", __name__, url_prefix="/API/Category")  
21 -  
22 -  
23 - @staticmethod  
24 - @bp.route('/Create', methods=['POST'])  
25 - @swag_from(catalog_create.Api.api_doc)  
26 - def catalog_create():  
27 - """  
28 - 创建目录  
29 - """  
30 - return catalog_create.Api().result  
31 -  
32 - @staticmethod  
33 - @bp.route('/Next', methods=['POST'])  
34 - @swag_from(catalog_next.Api.api_doc)  
35 - def catalog_next():  
36 - """  
37 - 下一级目录  
38 - """  
39 - return catalog_next.Api().result  
40 -  
41 - @staticmethod  
42 - @bp.route('/Tree', methods=['POST'])  
43 - @swag_from(catalog_tree.Api.api_doc)  
44 - def catalog_tree():  
45 - """  
46 - 目录树  
47 - """  
48 - return catalog_tree.Api().result  
49 -  
50 -  
51 - @staticmethod  
52 - @bp.route('/RealTree', methods=['POST'])  
53 - @swag_from(catalog_real_tree.Api.api_doc)  
54 - def catalog_real_tree():  
55 - """  
56 - 目录树  
57 - """  
58 - return catalog_real_tree.Api().result  
59 -  
60 -  
61 - @staticmethod  
62 - @bp.route('/Edit', methods=['POST'])  
63 - @swag_from(catalog_edit.Api.api_doc)  
64 - def catalog_edit():  
65 - """  
66 - 修改目录  
67 - """  
68 - return catalog_edit.Api().result  
69 -  
70 - @staticmethod  
71 - @bp.route('/Delete', methods=['POST'])  
72 - @swag_from(catalog_delete.Api.api_doc)  
73 - def catalog_delete():  
74 - """  
75 - 删除目录  
76 - """ 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/1
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from flasgger import swag_from
  8 +from flask import Blueprint
  9 +from app.util import BlueprintApi
  10 +from . import catalog_create
  11 +from . import catalog_next
  12 +from . import catalog_tree
  13 +from . import catalog_delete
  14 +from . import catalog_edit
  15 +from . import catalog_real_tree
  16 +
  17 +
  18 +class DataManager(BlueprintApi):
  19 +
  20 + bp = Blueprint("Category", __name__, url_prefix="/API/Category")
  21 +
  22 +
  23 + @staticmethod
  24 + @bp.route('/Create', methods=['POST'])
  25 + @swag_from(catalog_create.Api.api_doc)
  26 + def catalog_create():
  27 + """
  28 + 创建目录
  29 + """
  30 + return catalog_create.Api().result
  31 +
  32 + @staticmethod
  33 + @bp.route('/Next', methods=['POST'])
  34 + @swag_from(catalog_next.Api.api_doc)
  35 + def catalog_next():
  36 + """
  37 + 下一级目录
  38 + """
  39 + return catalog_next.Api().result
  40 +
  41 + @staticmethod
  42 + @bp.route('/Tree', methods=['POST'])
  43 + @swag_from(catalog_tree.Api.api_doc)
  44 + def catalog_tree():
  45 + """
  46 + 目录树
  47 + """
  48 + return catalog_tree.Api().result
  49 +
  50 +
  51 + @staticmethod
  52 + @bp.route('/RealTree', methods=['POST'])
  53 + @swag_from(catalog_real_tree.Api.api_doc)
  54 + def catalog_real_tree():
  55 + """
  56 + 目录树
  57 + """
  58 + return catalog_real_tree.Api().result
  59 +
  60 +
  61 + @staticmethod
  62 + @bp.route('/Edit', methods=['POST'])
  63 + @swag_from(catalog_edit.Api.api_doc)
  64 + def catalog_edit():
  65 + """
  66 + 修改目录
  67 + """
  68 + return catalog_edit.Api().result
  69 +
  70 + @staticmethod
  71 + @bp.route('/Delete', methods=['POST'])
  72 + @swag_from(catalog_delete.Api.api_doc)
  73 + def catalog_delete():
  74 + """
  75 + 删除目录
  76 + """
77 return catalog_delete.Api().result 77 return catalog_delete.Api().result
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -import uuid  
7 -from app.models import *  
8 -from app.util.component.ApiTemplate import ApiTemplate  
9 -class Api(ApiTemplate):  
10 - api_name = "创建目录"  
11 - def para_check(self):  
12 - if not self.para.get("database_guid"):  
13 - raise Exception("缺乏database_guid参数")  
14 - if not self.para.get("pguid"):  
15 - raise Exception("缺乏pguid参数")  
16 - if not self.para.get("name"):  
17 - raise Exception("缺乏name参数")  
18 -  
19 - def process(self):  
20 -  
21 - # 返回结果  
22 - res = {}  
23 - res["result"] = False  
24 - try:  
25 - # 业务逻辑  
26 -  
27 - if not Database.query.filter_by(guid=self.para.get("database_guid")).one_or_none():  
28 - res["msg"]="数据库不存在!"  
29 - return res  
30 -  
31 -  
32 - # 可以创建已有数据目录的子目录  
33 - # if Table.query.filter_by(catalog_guid=self.para.get("pguid")).all():  
34 - # raise Exception("父目录挂载了数据,不能创建子目录")  
35 -  
36 - if Catalog.query.filter_by(name=self.para.get("name"),pguid=self.para.get("pguid"),database_guid=self.para.get("database_guid")).one_or_none():  
37 - res["msg"]="目录已经存在!"  
38 - return res  
39 -  
40 -  
41 - # if Catalog.query.filter_by(pguid="0",database_guid=self.para.get("database_guid")).one_or_none() and self.para.get("pguid").__eq__("0"):  
42 - # raise Exception("只能有一个根目录!")  
43 -  
44 - guid = uuid.uuid1().__str__()  
45 - path = guid  
46 -  
47 - # 获得目录的全路径  
48 - pguid = self.para.get("pguid")  
49 - count = 0  
50 - while pguid !="0" and count<100:  
51 - count+=1  
52 - path = pguid+":"+path  
53 - p_catalog = Catalog.query.filter_by(guid=pguid).one_or_none()  
54 - pguid = p_catalog.pguid  
55 - if count==100:  
56 - raise Exception("目录结构出现问题!")  
57 - path = "0" + ":" + path  
58 -  
59 - sort = Catalog.query.filter_by(pguid=self.para.get("pguid")).count()  
60 -  
61 - catalog = Catalog(guid=guid,pguid=self.para.get("pguid"),name=self.para.get("name"),  
62 - sort=sort,description=self.para.get("description"),  
63 - database_guid=self.para.get("database_guid"),path=path)  
64 - db.session.add(catalog)  
65 - db.session.commit()  
66 -  
67 -  
68 - res["msg"] = "目录创建成功!"  
69 - res["data"] = guid  
70 - res["result"] = True  
71 - except Exception as e:  
72 - db.session.rollback()  
73 - raise e  
74 - return res  
75 -  
76 - api_doc={  
77 -  
78 - "tags":["目录接口"],  
79 - "parameters":[  
80 - {"name": "name",  
81 - "in": "formData",  
82 - "type": "string",  
83 - "description":"目录名"},  
84 - {"name": "pguid",  
85 - "in": "formData",  
86 - "type": "string","description":"父目录guid,创建根目录时为0"},  
87 - {"name": "database_guid",  
88 - "in": "formData",  
89 - "type": "string","description":"数据库guid"}  
90 -  
91 - ],  
92 - "responses":{  
93 - 200:{  
94 - "schema":{  
95 - "properties":{  
96 - }  
97 - }  
98 - }  
99 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +import uuid
  7 +from app.models import *
  8 +from app.util.component.ApiTemplate import ApiTemplate
  9 +class Api(ApiTemplate):
  10 + api_name = "创建目录"
  11 + def para_check(self):
  12 + if not self.para.get("database_guid"):
  13 + raise Exception("缺乏database_guid参数")
  14 + if not self.para.get("pguid"):
  15 + raise Exception("缺乏pguid参数")
  16 + if not self.para.get("name"):
  17 + raise Exception("缺乏name参数")
  18 +
  19 + def process(self):
  20 +
  21 + # 返回结果
  22 + res = {}
  23 + res["result"] = False
  24 + try:
  25 + # 业务逻辑
  26 +
  27 + if not Database.query.filter_by(guid=self.para.get("database_guid")).one_or_none():
  28 + res["msg"]="数据库不存在!"
  29 + return res
  30 +
  31 +
  32 + # 可以创建已有数据目录的子目录
  33 + # if Table.query.filter_by(catalog_guid=self.para.get("pguid")).all():
  34 + # raise Exception("父目录挂载了数据,不能创建子目录")
  35 +
  36 + if Catalog.query.filter_by(name=self.para.get("name"),pguid=self.para.get("pguid"),database_guid=self.para.get("database_guid")).one_or_none():
  37 + res["msg"]="目录已经存在!"
  38 + return res
  39 +
  40 +
  41 + # if Catalog.query.filter_by(pguid="0",database_guid=self.para.get("database_guid")).one_or_none() and self.para.get("pguid").__eq__("0"):
  42 + # raise Exception("只能有一个根目录!")
  43 +
  44 + guid = uuid.uuid1().__str__()
  45 + path = guid
  46 +
  47 + # 获得目录的全路径
  48 + pguid = self.para.get("pguid")
  49 + count = 0
  50 + while pguid !="0" and count<100:
  51 + count+=1
  52 + path = pguid+":"+path
  53 + p_catalog = Catalog.query.filter_by(guid=pguid).one_or_none()
  54 + pguid = p_catalog.pguid
  55 + if count==100:
  56 + raise Exception("目录结构出现问题!")
  57 + path = "0" + ":" + path
  58 +
  59 + sort = Catalog.query.filter_by(pguid=self.para.get("pguid")).count()
  60 +
  61 + catalog = Catalog(guid=guid,pguid=self.para.get("pguid"),name=self.para.get("name"),
  62 + sort=sort,description=self.para.get("description"),
  63 + database_guid=self.para.get("database_guid"),path=path)
  64 + db.session.add(catalog)
  65 + db.session.commit()
  66 +
  67 +
  68 + res["msg"] = "目录创建成功!"
  69 + res["data"] = guid
  70 + res["result"] = True
  71 + except Exception as e:
  72 + db.session.rollback()
  73 + raise e
  74 + return res
  75 +
  76 + api_doc={
  77 +
  78 + "tags":["目录接口"],
  79 + "parameters":[
  80 + {"name": "name",
  81 + "in": "formData",
  82 + "type": "string",
  83 + "description":"目录名"},
  84 + {"name": "pguid",
  85 + "in": "formData",
  86 + "type": "string","description":"父目录guid,创建根目录时为0"},
  87 + {"name": "database_guid",
  88 + "in": "formData",
  89 + "type": "string","description":"数据库guid"}
  90 +
  91 + ],
  92 + "responses":{
  93 + 200:{
  94 + "schema":{
  95 + "properties":{
  96 + }
  97 + }
  98 + }
  99 + }
100 } 100 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -  
8 -from app.models import *  
9 -from app.util.component.ApiTemplate import ApiTemplate  
10 -class Api(ApiTemplate):  
11 - api_name = "删除目录"  
12 - def process(self):  
13 -  
14 -  
15 - # 返回结果  
16 - res = {}  
17 - try:  
18 - # 业务逻辑  
19 -  
20 -  
21 - # 啥情况都能删  
22 - # if Table.query.filter_by(catalog_guid=self.para.get("guid")).all():  
23 - # raise Exception("目录挂载了数据,不可删除,可将数据移出目录后删除!")  
24 - # if Catalog.query.filter_by(pguid=self.para.get("guid")).all():  
25 - # raise Exception("目录非子目录,不可删除,请先将子目录删除!")  
26 -  
27 - catalog_guid = self.para.get("guid")  
28 -  
29 - catalog = Catalog.query.filter_by(guid=catalog_guid).one_or_none()  
30 - if not catalog:  
31 - res["msg"]="目录不存在!"  
32 - return res  
33 -  
34 - else:  
35 -  
36 - # 转移目录下的数据  
37 -  
38 - # # 删除根节点  
39 - # if catalog.pguid.__eq__("0"):  
40 - # database_guid = catalog.database_guid  
41 - # Table.query.filter_by(database_guid=database_guid).update({"catalog_guid": None})  
42 - # catalogs = Catalog.query.filter(Catalog.path.like("%" + catalog_guid + "%")).all()  
43 - # for cata in catalogs:  
44 - # db.session.delete(cata)  
45 - #  
46 - # # 获取所有子目录:  
47 - # else:  
48 -  
49 - pguid = catalog.pguid  
50 - # 所有目录  
51 - catalogs = Catalog.query.filter(Catalog.path.like("%" + catalog_guid + "%")).all()  
52 - for cata in catalogs:  
53 - if pguid.__eq__("0"):  
54 - Table.query.filter_by(catalog_guid=cata.guid).update({"catalog_guid": None})  
55 - db.session.delete(cata)  
56 - else:  
57 - Table.query.filter_by(catalog_guid=cata.guid).update({"catalog_guid": pguid})  
58 - db.session.delete(cata)  
59 -  
60 - db.session.commit()  
61 - res["msg"] = "目录删除成功!"  
62 - res["result"] = True  
63 - except Exception as e:  
64 - db.session.rollback()  
65 - raise e  
66 - return res  
67 -  
68 -  
69 - api_doc = {  
70 - "tags": ["目录接口"],  
71 - "parameters": [  
72 - {"name": "guid",  
73 - "in": "formData",  
74 - "type": "string",  
75 - "description": "目录guid", "required": "true"},  
76 - ],  
77 - "responses": {  
78 - 200: {  
79 - "schema": {  
80 - "properties": {  
81 - }  
82 - }  
83 - }  
84 - }  
85 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +
  8 +from app.models import *
  9 +from app.util.component.ApiTemplate import ApiTemplate
  10 +class Api(ApiTemplate):
  11 + api_name = "删除目录"
  12 + def process(self):
  13 +
  14 +
  15 + # 返回结果
  16 + res = {}
  17 + try:
  18 + # 业务逻辑
  19 +
  20 +
  21 + # 啥情况都能删
  22 + # if Table.query.filter_by(catalog_guid=self.para.get("guid")).all():
  23 + # raise Exception("目录挂载了数据,不可删除,可将数据移出目录后删除!")
  24 + # if Catalog.query.filter_by(pguid=self.para.get("guid")).all():
  25 + # raise Exception("目录非子目录,不可删除,请先将子目录删除!")
  26 +
  27 + catalog_guid = self.para.get("guid")
  28 +
  29 + catalog = Catalog.query.filter_by(guid=catalog_guid).one_or_none()
  30 + if not catalog:
  31 + res["msg"]="目录不存在!"
  32 + return res
  33 +
  34 + else:
  35 +
  36 + # 转移目录下的数据
  37 +
  38 + # # 删除根节点
  39 + # if catalog.pguid.__eq__("0"):
  40 + # database_guid = catalog.database_guid
  41 + # Table.query.filter_by(database_guid=database_guid).update({"catalog_guid": None})
  42 + # catalogs = Catalog.query.filter(Catalog.path.like("%" + catalog_guid + "%")).all()
  43 + # for cata in catalogs:
  44 + # db.session.delete(cata)
  45 + #
  46 + # # 获取所有子目录:
  47 + # else:
  48 +
  49 + pguid = catalog.pguid
  50 + # 所有目录
  51 + catalogs = Catalog.query.filter(Catalog.path.like("%" + catalog_guid + "%")).all()
  52 + for cata in catalogs:
  53 + if pguid.__eq__("0"):
  54 + Table.query.filter_by(catalog_guid=cata.guid).update({"catalog_guid": None})
  55 + db.session.delete(cata)
  56 + else:
  57 + Table.query.filter_by(catalog_guid=cata.guid).update({"catalog_guid": pguid})
  58 + db.session.delete(cata)
  59 +
  60 + db.session.commit()
  61 + res["msg"] = "目录删除成功!"
  62 + res["result"] = True
  63 + except Exception as e:
  64 + db.session.rollback()
  65 + raise e
  66 + return res
  67 +
  68 +
  69 + api_doc = {
  70 + "tags": ["目录接口"],
  71 + "parameters": [
  72 + {"name": "guid",
  73 + "in": "formData",
  74 + "type": "string",
  75 + "description": "目录guid", "required": "true"},
  76 + ],
  77 + "responses": {
  78 + 200: {
  79 + "schema": {
  80 + "properties": {
  81 + }
  82 + }
  83 + }
  84 + }
  85 + }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -from app.models import *  
7 -  
8 -from app.util.component.ApiTemplate import ApiTemplate  
9 -class Api(ApiTemplate):  
10 - api_name = "修改目录"  
11 - def process(self):  
12 -  
13 -  
14 - # 返回结果  
15 - res = {}  
16 - try:  
17 - # 业务逻辑  
18 - if not Catalog.query.filter_by(guid=self.para.get("guid")).one_or_none():  
19 - res["msg"]="目录不存在!"  
20 - res["result"]=False  
21 - return res  
22 - else:  
23 - if self.para.get("name"):  
24 - Catalog.query.filter_by(guid=self.para.get("guid")).update({"name":self.para.get("name")})  
25 - if self.para.__contains__("description"):  
26 - Catalog.query.filter_by(guid=self.para.get("guid")).update({"description":self.para.get("description")})  
27 - db.session.commit()  
28 - res["msg"] = "目录修改成功!"  
29 - res["result"] = True  
30 - except Exception as e:  
31 - db.session.rollback()  
32 - raise e  
33 - return res  
34 -  
35 -  
36 - api_doc = {  
37 - "tags": ["目录接口"],  
38 - "parameters": [  
39 - {"name": "guid",  
40 - "in": "formData",  
41 - "type": "string",  
42 - "description": "目录guid", "required": "true"},  
43 - {"name": "name",  
44 - "in": "formData",  
45 - "type": "string",  
46 - "description": "目录名", "required": "true"}  
47 - ],  
48 - "responses": {  
49 - 200: {  
50 - "schema": {  
51 - "properties": {  
52 - }  
53 - }  
54 - }  
55 - }  
56 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +from app.models import *
  7 +
  8 +from app.util.component.ApiTemplate import ApiTemplate
  9 +class Api(ApiTemplate):
  10 + api_name = "修改目录"
  11 + def process(self):
  12 +
  13 +
  14 + # 返回结果
  15 + res = {}
  16 + try:
  17 + # 业务逻辑
  18 + if not Catalog.query.filter_by(guid=self.para.get("guid")).one_or_none():
  19 + res["msg"]="目录不存在!"
  20 + res["result"]=False
  21 + return res
  22 + else:
  23 + if self.para.get("name"):
  24 + Catalog.query.filter_by(guid=self.para.get("guid")).update({"name":self.para.get("name")})
  25 + if self.para.__contains__("description"):
  26 + Catalog.query.filter_by(guid=self.para.get("guid")).update({"description":self.para.get("description")})
  27 + db.session.commit()
  28 + res["msg"] = "目录修改成功!"
  29 + res["result"] = True
  30 + except Exception as e:
  31 + db.session.rollback()
  32 + raise e
  33 + return res
  34 +
  35 +
  36 + api_doc = {
  37 + "tags": ["目录接口"],
  38 + "parameters": [
  39 + {"name": "guid",
  40 + "in": "formData",
  41 + "type": "string",
  42 + "description": "目录guid", "required": "true"},
  43 + {"name": "name",
  44 + "in": "formData",
  45 + "type": "string",
  46 + "description": "目录名", "required": "true"}
  47 + ],
  48 + "responses": {
  49 + 200: {
  50 + "schema": {
  51 + "properties": {
  52 + }
  53 + }
  54 + }
  55 + }
  56 + }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from app.models import *  
8 -  
9 -from app.util.component.ApiTemplate import ApiTemplate  
10 -from app.util.component.ModelVisitor import ModelVisitor  
11 -class Api(ApiTemplate):  
12 - api_name = "下一级目录"  
13 - def process(self):  
14 -  
15 - # 返回结果  
16 - res = {}  
17 - try:  
18 - # 业务逻辑  
19 -  
20 - res["data"] = []  
21 - catalogs = Catalog.query.filter_by(pguid=self.para.get("catalog_guid"),database_guid=self.para.get("database_guid")).all()  
22 - for cata in catalogs:  
23 - catalog_guids = [c.guid for c in Catalog.query.filter(Catalog.path.like("%" + cata.guid + "%")).all()]  
24 - table_count = Table.query.filter(Table.catalog_guid.in_(catalog_guids)).count()  
25 - database_alias = cata.relate_database.alias  
26 - cata_json = ModelVisitor.object_to_json(cata)  
27 - cata_json["table_count"]=table_count  
28 - cata_json["database_alias"] = database_alias  
29 -  
30 - res["data"].append(cata_json)  
31 - res["result"] = True  
32 - except Exception as e:  
33 - raise e  
34 - return res  
35 -  
36 - api_doc={  
37 -  
38 - "tags":["目录接口"],  
39 - "parameters":[  
40 - {"name": "catalog_guid",  
41 - "in": "formData",  
42 - "type": "string",  
43 - "description":"目录guid","required": "true"},  
44 - {"name": "database_guid",  
45 - "in": "formData",  
46 - "type": "string",  
47 - "description": "数据库guid", "required": "true"},  
48 -  
49 - ],  
50 - "responses":{  
51 - 200:{  
52 - "schema":{  
53 - "properties":{  
54 - }  
55 - }  
56 - }  
57 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from app.models import *
  8 +
  9 +from app.util.component.ApiTemplate import ApiTemplate
  10 +from app.util.component.ModelVisitor import ModelVisitor
  11 +class Api(ApiTemplate):
  12 + api_name = "下一级目录"
  13 + def process(self):
  14 +
  15 + # 返回结果
  16 + res = {}
  17 + try:
  18 + # 业务逻辑
  19 +
  20 + res["data"] = []
  21 + catalogs = Catalog.query.filter_by(pguid=self.para.get("catalog_guid"),database_guid=self.para.get("database_guid")).all()
  22 + for cata in catalogs:
  23 + catalog_guids = [c.guid for c in Catalog.query.filter(Catalog.path.like("%" + cata.guid + "%")).all()]
  24 + table_count = Table.query.filter(Table.catalog_guid.in_(catalog_guids)).count()
  25 + database_alias = cata.relate_database.alias
  26 + cata_json = ModelVisitor.object_to_json(cata)
  27 + cata_json["table_count"]=table_count
  28 + cata_json["database_alias"] = database_alias
  29 +
  30 + res["data"].append(cata_json)
  31 + res["result"] = True
  32 + except Exception as e:
  33 + raise e
  34 + return res
  35 +
  36 + api_doc={
  37 +
  38 + "tags":["目录接口"],
  39 + "parameters":[
  40 + {"name": "catalog_guid",
  41 + "in": "formData",
  42 + "type": "string",
  43 + "description":"目录guid","required": "true"},
  44 + {"name": "database_guid",
  45 + "in": "formData",
  46 + "type": "string",
  47 + "description": "数据库guid", "required": "true"},
  48 +
  49 + ],
  50 + "responses":{
  51 + 200:{
  52 + "schema":{
  53 + "properties":{
  54 + }
  55 + }
  56 + }
  57 + }
58 } 58 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from app.models import *  
8 -  
9 -from app.util.component.ApiTemplate import ApiTemplate  
10 -class Api(ApiTemplate):  
11 - api_name = "目录树"  
12 - def process(self):  
13 -  
14 - # 返回结果  
15 - res = {}  
16 - try:  
17 - # 业务逻辑  
18 - database_guid = self.para.get("database_guid")  
19 - catalogs = Catalog.query.filter_by(database_guid=database_guid).all()  
20 -  
21 - tree_origin = []  
22 - for cata in catalogs:  
23 - catalog_guids = [c.guid for c in Catalog.query.filter(Catalog.path.like("%" + cata.guid + "%")).all()]  
24 - table_count = Table.query.filter(Table.catalog_guid.in_(catalog_guids)).count()  
25 -  
26 - # cata_json = object_to_json(cata)  
27 - cata_json ={}  
28 - cata_json["database_guid"]=cata.database_guid  
29 - cata_json["description"] = cata.description  
30 - cata_json["guid"] = cata.guid  
31 - cata_json["name"] = cata.name  
32 - cata_json["path"] = cata.path  
33 - cata_json["pguid"] = cata.pguid  
34 - cata_json["sort"] = cata.sort  
35 - cata_json["table_count"]=table_count  
36 - cata_json["children"] = []  
37 - tree_origin.append(cata_json)  
38 -  
39 - for cata in tree_origin:  
40 - cata_pguid = cata["pguid"]  
41 - if not cata_pguid=="0":  
42 - for c in tree_origin:  
43 - if c["guid"].__eq__(cata_pguid):  
44 - c["children"].append(cata)  
45 -  
46 - res["data"] = [cata for cata in tree_origin if cata["pguid"].__eq__("0")]  
47 - res["result"] = True  
48 - except Exception as e:  
49 - raise e  
50 - return res  
51 -  
52 - api_doc={  
53 -  
54 - "tags":["目录接口"],  
55 - "parameters":[  
56 - {"name": "database_guid",  
57 - "in": "formData",  
58 - "type": "string",  
59 - "description": "数据库guid", "required": "true"},  
60 -  
61 - ],  
62 - "responses":{  
63 - 200:{  
64 - "schema":{  
65 - "properties":{  
66 - }  
67 - }  
68 - }  
69 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from app.models import *
  8 +
  9 +from app.util.component.ApiTemplate import ApiTemplate
  10 +class Api(ApiTemplate):
  11 + api_name = "目录树"
  12 + def process(self):
  13 +
  14 + # 返回结果
  15 + res = {}
  16 + try:
  17 + # 业务逻辑
  18 + database_guid = self.para.get("database_guid")
  19 + catalogs = Catalog.query.filter_by(database_guid=database_guid).all()
  20 +
  21 + tree_origin = []
  22 + for cata in catalogs:
  23 + catalog_guids = [c.guid for c in Catalog.query.filter(Catalog.path.like("%" + cata.guid + "%")).all()]
  24 + table_count = Table.query.filter(Table.catalog_guid.in_(catalog_guids)).count()
  25 +
  26 + # cata_json = object_to_json(cata)
  27 + cata_json ={}
  28 + cata_json["database_guid"]=cata.database_guid
  29 + cata_json["description"] = cata.description
  30 + cata_json["guid"] = cata.guid
  31 + cata_json["name"] = cata.name
  32 + cata_json["path"] = cata.path
  33 + cata_json["pguid"] = cata.pguid
  34 + cata_json["sort"] = cata.sort
  35 + cata_json["table_count"]=table_count
  36 + cata_json["children"] = []
  37 + tree_origin.append(cata_json)
  38 +
  39 + for cata in tree_origin:
  40 + cata_pguid = cata["pguid"]
  41 + if not cata_pguid=="0":
  42 + for c in tree_origin:
  43 + if c["guid"].__eq__(cata_pguid):
  44 + c["children"].append(cata)
  45 +
  46 + res["data"] = [cata for cata in tree_origin if cata["pguid"].__eq__("0")]
  47 + res["result"] = True
  48 + except Exception as e:
  49 + raise e
  50 + return res
  51 +
  52 + api_doc={
  53 +
  54 + "tags":["目录接口"],
  55 + "parameters":[
  56 + {"name": "database_guid",
  57 + "in": "formData",
  58 + "type": "string",
  59 + "description": "数据库guid", "required": "true"},
  60 +
  61 + ],
  62 + "responses":{
  63 + 200:{
  64 + "schema":{
  65 + "properties":{
  66 + }
  67 + }
  68 + }
  69 + }
70 } 70 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from app.models import *  
8 -  
9 -from app.util.component.ApiTemplate import ApiTemplate  
10 -class Api(ApiTemplate):  
11 - api_name = "目录"  
12 - def process(self):  
13 -  
14 - # 返回结果  
15 - res = {}  
16 - try:  
17 - # 业务逻辑  
18 - database_guid = self.para.get("database_guid")  
19 - catalogs = Catalog.query.filter_by(database_guid=database_guid).all()  
20 - res["data"]=[]  
21 - for cata in catalogs:  
22 - catalog_guids = [c.guid for c in Catalog.query.filter(Catalog.path.like("%" + cata.guid + "%")).all()]  
23 - table_count = Table.query.filter(Table.catalog_guid.in_(catalog_guids)).count()  
24 -  
25 - # cata_json = object_to_json(cata)  
26 - cata_json ={}  
27 - cata_json["database_guid"]=cata.database_guid  
28 - cata_json["description"] = cata.description  
29 - cata_json["guid"] = cata.guid  
30 - cata_json["name"] = cata.name  
31 - cata_json["path"] = cata.path  
32 - cata_json["pguid"] = cata.pguid  
33 - cata_json["sort"] = cata.sort  
34 - cata_json["table_count"]=table_count  
35 - res["data"].append(cata_json)  
36 -  
37 - res["result"] = True  
38 -  
39 - except Exception as e:  
40 - raise e  
41 - return res  
42 -  
43 - api_doc={  
44 -  
45 - "tags":["目录接口"],  
46 - "parameters":[  
47 - {"name": "database_guid",  
48 - "in": "formData",  
49 - "type": "string",  
50 - "description": "数据库guid", "required": "true"},  
51 -  
52 - ],  
53 - "responses":{  
54 - 200:{  
55 - "schema":{  
56 - "properties":{  
57 - }  
58 - }  
59 - }  
60 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from app.models import *
  8 +
  9 +from app.util.component.ApiTemplate import ApiTemplate
  10 +class Api(ApiTemplate):
  11 + api_name = "目录"
  12 + def process(self):
  13 +
  14 + # 返回结果
  15 + res = {}
  16 + try:
  17 + # 业务逻辑
  18 + database_guid = self.para.get("database_guid")
  19 + catalogs = Catalog.query.filter_by(database_guid=database_guid).all()
  20 + res["data"]=[]
  21 + for cata in catalogs:
  22 + catalog_guids = [c.guid for c in Catalog.query.filter(Catalog.path.like("%" + cata.guid + "%")).all()]
  23 + table_count = Table.query.filter(Table.catalog_guid.in_(catalog_guids)).count()
  24 +
  25 + # cata_json = object_to_json(cata)
  26 + cata_json ={}
  27 + cata_json["database_guid"]=cata.database_guid
  28 + cata_json["description"] = cata.description
  29 + cata_json["guid"] = cata.guid
  30 + cata_json["name"] = cata.name
  31 + cata_json["path"] = cata.path
  32 + cata_json["pguid"] = cata.pguid
  33 + cata_json["sort"] = cata.sort
  34 + cata_json["table_count"]=table_count
  35 + res["data"].append(cata_json)
  36 +
  37 + res["result"] = True
  38 +
  39 + except Exception as e:
  40 + raise e
  41 + return res
  42 +
  43 + api_doc={
  44 +
  45 + "tags":["目录接口"],
  46 + "parameters":[
  47 + {"name": "database_guid",
  48 + "in": "formData",
  49 + "type": "string",
  50 + "description": "数据库guid", "required": "true"},
  51 +
  52 + ],
  53 + "responses":{
  54 + 200:{
  55 + "schema":{
  56 + "properties":{
  57 + }
  58 + }
  59 + }
  60 + }
61 } 61 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -  
8 -from flasgger import swag_from  
9 -from flask import Blueprint  
10 -from app.util import BlueprintApi  
11 -  
12 -from . import database_register  
13 -from . import database_test  
14 -from . import database_list  
15 -from . import database_delete  
16 -from . import database_edit  
17 -from . import database_alias_check  
18 -from . import database_connect_test  
19 -from . import database_info  
20 -  
21 -class DataManager(BlueprintApi):  
22 -  
23 - bp = Blueprint("Database", __name__, url_prefix="/API/Database")  
24 -  
25 -  
26 - @staticmethod  
27 - @bp.route('/Register', methods=['POST'])  
28 - @swag_from(database_register.Api.api_doc)  
29 - def api_database_register():  
30 - """  
31 - 数据源注册  
32 - """  
33 - return database_register.Api().result  
34 -  
35 - @staticmethod  
36 - @bp.route('/List', methods=['POST'])  
37 - @swag_from(database_list.Api.api_doc)  
38 - def api_database_list():  
39 - """  
40 - 数据源列表  
41 - """  
42 - return database_list.Api().result  
43 -  
44 - @staticmethod  
45 - @bp.route('/Delete', methods=['POST'])  
46 - @swag_from(database_delete.Api.api_doc)  
47 - def api_database_delete():  
48 - """  
49 - 数据源注销  
50 - """  
51 - return database_delete.Api().result  
52 -  
53 - @staticmethod  
54 - @bp.route('/Edit', methods=['POST'])  
55 - @swag_from(database_edit.Api.api_doc)  
56 - def database_edit():  
57 - """  
58 - 修改数据源  
59 - """  
60 - return database_edit.Api().result  
61 -  
62 - @staticmethod  
63 - @bp.route('/Test', methods=['POST'])  
64 - @swag_from(database_test.Api.api_doc)  
65 - def api_database_test():  
66 - """  
67 - 数据源测试  
68 - """  
69 - return database_test.Api().result  
70 -  
71 - @staticmethod  
72 - @bp.route('/CheckAlias', methods=['POST'])  
73 - @swag_from(database_alias_check.Api.api_doc)  
74 - def api_database_alias_check():  
75 - """  
76 - 数据源别名测试  
77 - """  
78 - return database_alias_check.Api().result  
79 -  
80 - @staticmethod  
81 - @bp.route('/CheckConnect', methods=['POST'])  
82 - @swag_from(database_connect_test.Api.api_doc)  
83 - def api_database_connect_test():  
84 - """  
85 - 数据源连接测试  
86 - """  
87 - return database_connect_test.Api().result  
88 -  
89 -  
90 - @staticmethod  
91 - @bp.route('/Info', methods=['POST'])  
92 - @swag_from(database_info.Api.api_doc)  
93 - def api_database_info():  
94 - """  
95 - 数据源信息  
96 - """ 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +
  8 +from flasgger import swag_from
  9 +from flask import Blueprint
  10 +from app.util import BlueprintApi
  11 +
  12 +from . import database_register
  13 +from . import database_test
  14 +from . import database_list
  15 +from . import database_delete
  16 +from . import database_edit
  17 +from . import database_alias_check
  18 +from . import database_connect_test
  19 +from . import database_info
  20 +
  21 +class DataManager(BlueprintApi):
  22 +
  23 + bp = Blueprint("Database", __name__, url_prefix="/API/Database")
  24 +
  25 +
  26 + @staticmethod
  27 + @bp.route('/Register', methods=['POST'])
  28 + @swag_from(database_register.Api.api_doc)
  29 + def api_database_register():
  30 + """
  31 + 数据源注册
  32 + """
  33 + return database_register.Api().result
  34 +
  35 + @staticmethod
  36 + @bp.route('/List', methods=['POST'])
  37 + @swag_from(database_list.Api.api_doc)
  38 + def api_database_list():
  39 + """
  40 + 数据源列表
  41 + """
  42 + return database_list.Api().result
  43 +
  44 + @staticmethod
  45 + @bp.route('/Delete', methods=['POST'])
  46 + @swag_from(database_delete.Api.api_doc)
  47 + def api_database_delete():
  48 + """
  49 + 数据源注销
  50 + """
  51 + return database_delete.Api().result
  52 +
  53 + @staticmethod
  54 + @bp.route('/Edit', methods=['POST'])
  55 + @swag_from(database_edit.Api.api_doc)
  56 + def database_edit():
  57 + """
  58 + 修改数据源
  59 + """
  60 + return database_edit.Api().result
  61 +
  62 + @staticmethod
  63 + @bp.route('/Test', methods=['POST'])
  64 + @swag_from(database_test.Api.api_doc)
  65 + def api_database_test():
  66 + """
  67 + 数据源测试
  68 + """
  69 + return database_test.Api().result
  70 +
  71 + @staticmethod
  72 + @bp.route('/CheckAlias', methods=['POST'])
  73 + @swag_from(database_alias_check.Api.api_doc)
  74 + def api_database_alias_check():
  75 + """
  76 + 数据源别名测试
  77 + """
  78 + return database_alias_check.Api().result
  79 +
  80 + @staticmethod
  81 + @bp.route('/CheckConnect', methods=['POST'])
  82 + @swag_from(database_connect_test.Api.api_doc)
  83 + def api_database_connect_test():
  84 + """
  85 + 数据源连接测试
  86 + """
  87 + return database_connect_test.Api().result
  88 +
  89 +
  90 + @staticmethod
  91 + @bp.route('/Info', methods=['POST'])
  92 + @swag_from(database_info.Api.api_doc)
  93 + def api_database_info():
  94 + """
  95 + 数据源信息
  96 + """
97 return database_info.Api().result 97 return database_info.Api().result
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -from app.models import Database,db  
7 -  
8 -  
9 -  
10 -from app.util.component.ApiTemplate import ApiTemplate  
11 -class Api(ApiTemplate):  
12 - api_name = "测试数据库别名"  
13 -  
14 - def process(self):  
15 - res ={}  
16 - try:  
17 - database = db.session.query(Database).filter_by(alias=self.para.get("alias")).one_or_none()  
18 - if database:  
19 - res["msg"]="数据库重名!"  
20 - res["result"]=False  
21 - else:  
22 - res["result"] = True  
23 - except Exception as e:  
24 - raise e  
25 - return res  
26 -  
27 - api_doc={  
28 - "tags":["数据库接口"],  
29 - "parameters":[  
30 - {"name": "alias",  
31 - "in": "formData",  
32 - "type": "string","description":"数据库别名","required": "true"},  
33 -  
34 - ],  
35 - "responses":{  
36 - 200:{  
37 - "schema":{  
38 - "properties":{  
39 - }  
40 - }  
41 - }  
42 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +from app.models import Database,db
  7 +
  8 +
  9 +
  10 +from app.util.component.ApiTemplate import ApiTemplate
  11 +class Api(ApiTemplate):
  12 + api_name = "测试数据库别名"
  13 +
  14 + def process(self):
  15 + res ={}
  16 + try:
  17 + database = db.session.query(Database).filter_by(alias=self.para.get("alias")).one_or_none()
  18 + if database:
  19 + res["msg"]="数据库重名!"
  20 + res["result"]=False
  21 + else:
  22 + res["result"] = True
  23 + except Exception as e:
  24 + raise e
  25 + return res
  26 +
  27 + api_doc={
  28 + "tags":["数据库接口"],
  29 + "parameters":[
  30 + {"name": "alias",
  31 + "in": "formData",
  32 + "type": "string","description":"数据库别名","required": "true"},
  33 +
  34 + ],
  35 + "responses":{
  36 + 200:{
  37 + "schema":{
  38 + "properties":{
  39 + }
  40 + }
  41 + }
  42 + }
43 } 43 }
1 -# coding=utf-8  
2 -# author: 4N  
3 -# createtime: 2020/6/22  
4 -# email: nheweijun@sina.com  
5 -from contextlib import closing  
6 -  
7 -from sqlalchemy import create_engine  
8 -  
9 -from app.models import DES,Database  
10 -  
11 -  
12 -from app.util.component.ApiTemplate import ApiTemplate  
13 -class Api(ApiTemplate):  
14 - api_name = "测试数据库连接"  
15 - def process(self):  
16 - res = {}  
17 - try:  
18 - guid = self.para.get("guid")  
19 - database = Database.query.filter_by(guid=guid)  
20 - dbase:Database = database.one_or_none()  
21 - engine = create_engine(DES.decode(dbase.sqlalchemy_uri), connect_args={'connect_timeout': 1})  
22 - with closing(engine.connect()):  
23 - pass  
24 - res["result"]=True  
25 - res["msg"] = "测试连接成功!"  
26 - except:  
27 - raise Exception("测试连接失败!")  
28 - return res  
29 -  
30 - api_doc={  
31 - "tags":["数据库接口"],  
32 - "parameters":[  
33 -  
34 - {"name": "guid",  
35 - "in": "formData",  
36 - "type": "string", "required": "true"},  
37 -  
38 -  
39 - ],  
40 - "responses":{  
41 - 200:{  
42 - "schema":{  
43 - "properties":{  
44 - }  
45 - }  
46 - }  
47 - } 1 +# coding=utf-8
  2 +# author: 4N
  3 +# createtime: 2020/6/22
  4 +# email: nheweijun@sina.com
  5 +from contextlib import closing
  6 +
  7 +from sqlalchemy import create_engine
  8 +
  9 +from app.models import DES,Database
  10 +
  11 +
  12 +from app.util.component.ApiTemplate import ApiTemplate
  13 +class Api(ApiTemplate):
  14 + api_name = "测试数据库连接"
  15 + def process(self):
  16 + res = {}
  17 + try:
  18 + guid = self.para.get("guid")
  19 + database = Database.query.filter_by(guid=guid)
  20 + dbase:Database = database.one_or_none()
  21 + engine = create_engine(DES.decode(dbase.sqlalchemy_uri), connect_args={'connect_timeout': 1})
  22 + with closing(engine.connect()):
  23 + pass
  24 + res["result"]=True
  25 + res["msg"] = "测试连接成功!"
  26 + except:
  27 + raise Exception("测试连接失败!")
  28 + return res
  29 +
  30 + api_doc={
  31 + "tags":["数据库接口"],
  32 + "parameters":[
  33 +
  34 + {"name": "guid",
  35 + "in": "formData",
  36 + "type": "string", "required": "true"},
  37 +
  38 +
  39 + ],
  40 + "responses":{
  41 + 200:{
  42 + "schema":{
  43 + "properties":{
  44 + }
  45 + }
  46 + }
  47 + }
48 } 48 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from app.models import Database,db  
8 -  
9 -  
10 -from app.util.component.ApiTemplate import ApiTemplate  
11 -class Api(ApiTemplate):  
12 - api_name = "删除数据库"  
13 - def process(self):  
14 - res ={}  
15 - try:  
16 -  
17 - database = db.session.query(Database).filter_by(guid=self.para.get("guid")).one_or_none()  
18 - if database:  
19 - db.session.delete(database)  
20 - db.session.commit()  
21 - res["msg"] = "数据库删除成功!"  
22 - res["result"] = True  
23 - else:  
24 - res["msg"] = "数据库不存在!"  
25 - res["result"] = False  
26 - except Exception as e:  
27 - db.session.rollback()  
28 - raise e  
29 - return res  
30 -  
31 -  
32 -  
33 - api_doc={  
34 - "tags":["数据库接口"],  
35 - "parameters":[  
36 - {"name": "guid",  
37 - "in": "formData",  
38 - "type": "string","description":"数据库guid","required": "true"},  
39 -  
40 - ],  
41 - "responses":{  
42 - 200:{  
43 - "schema":{  
44 - "properties":{  
45 - }  
46 - }  
47 - }  
48 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from app.models import Database,db
  8 +
  9 +
  10 +from app.util.component.ApiTemplate import ApiTemplate
  11 +class Api(ApiTemplate):
  12 + api_name = "删除数据库"
  13 + def process(self):
  14 + res ={}
  15 + try:
  16 +
  17 + database = db.session.query(Database).filter_by(guid=self.para.get("guid")).one_or_none()
  18 + if database:
  19 + db.session.delete(database)
  20 + db.session.commit()
  21 + res["msg"] = "数据库删除成功!"
  22 + res["result"] = True
  23 + else:
  24 + res["msg"] = "数据库不存在!"
  25 + res["result"] = False
  26 + except Exception as e:
  27 + db.session.rollback()
  28 + raise e
  29 + return res
  30 +
  31 +
  32 +
  33 + api_doc={
  34 + "tags":["数据库接口"],
  35 + "parameters":[
  36 + {"name": "guid",
  37 + "in": "formData",
  38 + "type": "string","description":"数据库guid","required": "true"},
  39 +
  40 + ],
  41 + "responses":{
  42 + 200:{
  43 + "schema":{
  44 + "properties":{
  45 + }
  46 + }
  47 + }
  48 + }
49 } 49 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -  
6 -from app.models import Database,db  
7 -from contextlib import closing  
8 -  
9 -from sqlalchemy import create_engine  
10 -  
11 -from app.models import DES  
12 -import datetime  
13 -from . import database_alias_check  
14 -  
15 -from app.util.component.ApiTemplate import ApiTemplate  
16 -  
17 -from app.util.component.PGUtil import PGUtil  
18 -class Api(ApiTemplate):  
19 - api_name = "修改数据库"  
20 - def process(self):  
21 -  
22 - res = {}  
23 - res["result"] = False  
24 - try:  
25 - guid = self.para.get("guid")  
26 - alias = self.para.get("alias")  
27 -  
28 - passwd = self.para.get("passwd")  
29 - database = Database.query.filter_by(guid=guid)  
30 - dbase:Database = database.one_or_none()  
31 -  
32 - update_dict={}  
33 -  
34 - if not dbase:  
35 - res["msg"] = "数据库不存在!"  
36 - return res  
37 - if not alias and not passwd:  
38 - res["msg"] = "请填写参数!"  
39 - return res  
40 -  
41 -  
42 - if alias:  
43 - # 检测一波别名  
44 - check_alias = database_alias_check.Api().result  
45 - if not check_alias["result"]:  
46 - return check_alias  
47 - update_dict["alias"]=alias  
48 -  
49 - if passwd:  
50 - try:  
51 - user, password, host, port, database = PGUtil.get_info_from_sqlachemy_uri(DES.decode(dbase.sqlalchemy_uri))  
52 -  
53 - sqlalchemy_uri = "postgresql://{}:{}@{}:{}/{}".format(user, passwd,host,  
54 - port, database)  
55 -  
56 - connectsrt = "hostaddr={} port={} dbname='{}' user='{}' password='{}'".format(host, port, database, user,  
57 - passwd)  
58 - engine = create_engine(sqlalchemy_uri, connect_args={'connect_timeout': 2})  
59 - with closing(engine.connect()):  
60 - pass  
61 -  
62 - except :  
63 - res["msg"] = "密码错误!"  
64 - return res  
65 -  
66 - update_dict["sqlalchemy_uri"]= DES.encode(sqlalchemy_uri)  
67 - update_dict["connectstr"] = DES.encode(connectsrt)  
68 -  
69 - if update_dict:  
70 - update_dict["update_time"]=datetime.datetime.now()  
71 - Database.query.filter_by(guid=guid).update(update_dict)  
72 - db.session.commit()  
73 - res["result"] = True  
74 - res["msg"] = "数据修改成功!"  
75 - except Exception as e:  
76 - db.session.rollback()  
77 - raise e  
78 - return res  
79 -  
80 -  
81 -  
82 - api_doc={  
83 - "tags":["数据库接口"],  
84 - "parameters":[  
85 - {"name": "guid",  
86 - "in": "formData",  
87 - "type": "string"},  
88 - {"name": "alias",  
89 - "in": "formData",  
90 - "type": "string","description":"数据库别名"},  
91 - {"name": "passwd",  
92 - "in": "formData",  
93 - "type": "string", "description": "数据库密码"}  
94 - ],  
95 - "responses":{  
96 - 200:{  
97 - "schema":{  
98 - "properties":{  
99 - }  
100 - }  
101 - }  
102 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +
  6 +from app.models import Database,db
  7 +from contextlib import closing
  8 +
  9 +from sqlalchemy import create_engine
  10 +
  11 +from app.models import DES
  12 +import datetime
  13 +from . import database_alias_check
  14 +
  15 +from app.util.component.ApiTemplate import ApiTemplate
  16 +
  17 +from app.util.component.PGUtil import PGUtil
  18 +class Api(ApiTemplate):
  19 + api_name = "修改数据库"
  20 + def process(self):
  21 +
  22 + res = {}
  23 + res["result"] = False
  24 + try:
  25 + guid = self.para.get("guid")
  26 + alias = self.para.get("alias")
  27 +
  28 + passwd = self.para.get("passwd")
  29 + database = Database.query.filter_by(guid=guid)
  30 + dbase:Database = database.one_or_none()
  31 +
  32 + update_dict={}
  33 +
  34 + if not dbase:
  35 + res["msg"] = "数据库不存在!"
  36 + return res
  37 + if not alias and not passwd:
  38 + res["msg"] = "请填写参数!"
  39 + return res
  40 +
  41 +
  42 + if alias:
  43 + # 检测一波别名
  44 + check_alias = database_alias_check.Api().result
  45 + if not check_alias["result"]:
  46 + return check_alias
  47 + update_dict["alias"]=alias
  48 +
  49 + if passwd:
  50 + try:
  51 + user, password, host, port, database = PGUtil.get_info_from_sqlachemy_uri(DES.decode(dbase.sqlalchemy_uri))
  52 +
  53 + sqlalchemy_uri = "postgresql://{}:{}@{}:{}/{}".format(user, passwd,host,
  54 + port, database)
  55 +
  56 + connectsrt = "hostaddr={} port={} dbname='{}' user='{}' password='{}'".format(host, port, database, user,
  57 + passwd)
  58 + engine = create_engine(sqlalchemy_uri, connect_args={'connect_timeout': 2})
  59 + with closing(engine.connect()):
  60 + pass
  61 +
  62 + except :
  63 + res["msg"] = "密码错误!"
  64 + return res
  65 +
  66 + update_dict["sqlalchemy_uri"]= DES.encode(sqlalchemy_uri)
  67 + update_dict["connectstr"] = DES.encode(connectsrt)
  68 +
  69 + if update_dict:
  70 + update_dict["update_time"]=datetime.datetime.now()
  71 + Database.query.filter_by(guid=guid).update(update_dict)
  72 + db.session.commit()
  73 + res["result"] = True
  74 + res["msg"] = "数据修改成功!"
  75 + except Exception as e:
  76 + db.session.rollback()
  77 + raise e
  78 + return res
  79 +
  80 +
  81 +
  82 + api_doc={
  83 + "tags":["数据库接口"],
  84 + "parameters":[
  85 + {"name": "guid",
  86 + "in": "formData",
  87 + "type": "string"},
  88 + {"name": "alias",
  89 + "in": "formData",
  90 + "type": "string","description":"数据库别名"},
  91 + {"name": "passwd",
  92 + "in": "formData",
  93 + "type": "string", "description": "数据库密码"}
  94 + ],
  95 + "responses":{
  96 + 200:{
  97 + "schema":{
  98 + "properties":{
  99 + }
  100 + }
  101 + }
  102 + }
103 } 103 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -from app.models import Database,DES  
6 -from contextlib import closing  
7 -from sqlalchemy import create_engine,or_  
8 -  
9 -from app.models import Database,Catalog,Table  
10 -  
11 -  
12 -from app.util.component.ApiTemplate import ApiTemplate  
13 -  
14 -  
15 -class Api(ApiTemplate):  
16 - api_name = "获取数据库信息"  
17 - def process(self):  
18 - # 返回结果  
19 - res = {}  
20 - try:  
21 - # 业务逻辑  
22 - database_guid = self.para.get("guid")  
23 - table_type = self.para.get("table_type")  
24 - catalogs = Catalog.query.filter_by(database_guid=database_guid).all()  
25 -  
26 - tree_origin = []  
27 - for cata in catalogs:  
28 - cata_json = {}  
29 - cata_json["type"] = "catalog"  
30 - cata_json["guid"] = cata.guid  
31 - cata_json["name"] = cata.name  
32 - cata_json["pguid"] = cata.pguid  
33 - cata_json["children"] = []  
34 - tree_origin.append(cata_json)  
35 -  
36 - #挂接表  
37 - tables =Table.query.filter_by(database_guid=database_guid,catalog_guid=cata.guid).filter(Table.table_type != 0)  
38 - if table_type:  
39 - tables = tables.filter_by(table_type=table_type)  
40 - tables = tables.order_by(Table.name).all()  
41 -  
42 - for table in tables:  
43 - table_json= {}  
44 - table_json["name"]=table.name  
45 - table_json["alias"] = table.alias  
46 - table_json["guid"] = table.guid  
47 - table_json["type"] = "table"  
48 - table_json["table_type"] = table.table_type  
49 - cata_json["children"].append(table_json)  
50 -  
51 - for cata in tree_origin:  
52 - cata_pguid = cata["pguid"]  
53 - if not cata_pguid == "0":  
54 - for c in tree_origin:  
55 - if c["guid"].__eq__(cata_pguid):  
56 - c["children"].append(cata)  
57 - res["data"] = [cata for cata in tree_origin if cata["pguid"].__eq__("0")]  
58 -  
59 - # 挂接表  
60 - tables = Table.query.filter_by(database_guid=database_guid, catalog_guid=None).filter(  
61 - Table.table_type != 0)  
62 - if table_type:  
63 - tables = tables.filter_by(table_type=table_type)  
64 - tables = tables.order_by(Table.name).all()  
65 -  
66 - for table in tables:  
67 - table_json = {}  
68 - table_json["name"] = table.name  
69 - table_json["alias"] = table.alias  
70 - table_json["guid"] = table.guid  
71 - table_json["type"] = "table"  
72 - table_json["table_type"] = table.table_type  
73 - res["data"].append(table_json)  
74 -  
75 - res["result"] = True  
76 - except Exception as e:  
77 - raise e  
78 - return res  
79 -  
80 - api_doc={  
81 - "tags":["数据库接口"],  
82 - "parameters":[  
83 - {"name": "guid",  
84 - "in": "formData",  
85 - "type": "string", "description": "数据库guid"},  
86 - {"name": "table_type",  
87 - "in": "formData",  
88 - "type": "int", "description": "表类型","enum":[1,2,3]}  
89 - ],  
90 - "responses":{  
91 - 200:{  
92 - "schema":{  
93 - "properties":{  
94 - }  
95 - }  
96 - }  
97 - }  
98 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +from app.models import Database,DES
  6 +from contextlib import closing
  7 +from sqlalchemy import create_engine,or_
  8 +
  9 +from app.models import Database,Catalog,Table
  10 +
  11 +
  12 +from app.util.component.ApiTemplate import ApiTemplate
  13 +
  14 +
  15 +class Api(ApiTemplate):
  16 + api_name = "获取数据库信息"
  17 + def process(self):
  18 + # 返回结果
  19 + res = {}
  20 + try:
  21 + # 业务逻辑
  22 + database_guid = self.para.get("guid")
  23 + table_type = self.para.get("table_type")
  24 + catalogs = Catalog.query.filter_by(database_guid=database_guid).all()
  25 +
  26 + tree_origin = []
  27 + for cata in catalogs:
  28 + cata_json = {}
  29 + cata_json["type"] = "catalog"
  30 + cata_json["guid"] = cata.guid
  31 + cata_json["name"] = cata.name
  32 + cata_json["pguid"] = cata.pguid
  33 + cata_json["children"] = []
  34 + tree_origin.append(cata_json)
  35 +
  36 + #挂接表
  37 + tables =Table.query.filter_by(database_guid=database_guid,catalog_guid=cata.guid).filter(Table.table_type != 0)
  38 + if table_type:
  39 + tables = tables.filter_by(table_type=table_type)
  40 + tables = tables.order_by(Table.name).all()
  41 +
  42 + for table in tables:
  43 + table_json= {}
  44 + table_json["name"]=table.name
  45 + table_json["alias"] = table.alias
  46 + table_json["guid"] = table.guid
  47 + table_json["type"] = "table"
  48 + table_json["table_type"] = table.table_type
  49 + cata_json["children"].append(table_json)
  50 +
  51 + for cata in tree_origin:
  52 + cata_pguid = cata["pguid"]
  53 + if not cata_pguid == "0":
  54 + for c in tree_origin:
  55 + if c["guid"].__eq__(cata_pguid):
  56 + c["children"].append(cata)
  57 + res["data"] = [cata for cata in tree_origin if cata["pguid"].__eq__("0")]
  58 +
  59 + # 挂接表
  60 + tables = Table.query.filter_by(database_guid=database_guid, catalog_guid=None).filter(
  61 + Table.table_type != 0)
  62 + if table_type:
  63 + tables = tables.filter_by(table_type=table_type)
  64 + tables = tables.order_by(Table.name).all()
  65 +
  66 + for table in tables:
  67 + table_json = {}
  68 + table_json["name"] = table.name
  69 + table_json["alias"] = table.alias
  70 + table_json["guid"] = table.guid
  71 + table_json["type"] = "table"
  72 + table_json["table_type"] = table.table_type
  73 + res["data"].append(table_json)
  74 +
  75 + res["result"] = True
  76 + except Exception as e:
  77 + raise e
  78 + return res
  79 +
  80 + api_doc={
  81 + "tags":["数据库接口"],
  82 + "parameters":[
  83 + {"name": "guid",
  84 + "in": "formData",
  85 + "type": "string", "description": "数据库guid"},
  86 + {"name": "table_type",
  87 + "in": "formData",
  88 + "type": "int", "description": "表类型","enum":[1,2,3]}
  89 + ],
  90 + "responses":{
  91 + 200:{
  92 + "schema":{
  93 + "properties":{
  94 + }
  95 + }
  96 + }
  97 + }
  98 + }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -from app.models import Database,DES  
6 -from contextlib import closing  
7 -from sqlalchemy import create_engine  
8 -  
9 -from app.models import Database  
10 -  
11 -  
12 -from app.util.component.ApiTemplate import ApiTemplate  
13 -from app.util.component.ModelVisitor import ModelVisitor  
14 -class Api(ApiTemplate):  
15 - api_name = "获取数据库列表"  
16 - def process(self):  
17 - res = {}  
18 - res["data"]={}  
19 - try:  
20 - page_index = int(self.para.get("pageIndex", "0"))  
21 - page_size = int(self.para.get("pageSize", "10"))  
22 - alias = self.para.get("alias")  
23 - database_guid = self.para.get("guid")  
24 - database = Database.query.order_by(Database.create_time.desc())  
25 -  
26 - if alias:  
27 - database = database.filter(Database.alias.like("%" + alias + "%"))  
28 - if database_guid:  
29 - database = database.filter_by(guid = database_guid)  
30 -  
31 - res["data"]["count"] = database.count()  
32 -  
33 - database = database.limit(page_size).offset(page_index * page_size).all()  
34 - res["data"]["list"] =[]  
35 - for datab in database:  
36 - # 测试连接  
37 - try:  
38 - engine = create_engine(DES.decode(datab.sqlalchemy_uri), connect_args={'connect_timeout': 1})  
39 - with closing(engine.connect()):  
40 - pass  
41 - available=1  
42 - except:  
43 - available=-1  
44 - table_count = datab.relate_tables.count()  
45 - datab_json = ModelVisitor.database_to_json(datab)  
46 - datab_json["table_count"] = table_count  
47 - datab_json["available"] = available  
48 - res["data"]["list"].append(datab_json)  
49 -  
50 - # 可用非可用排序  
51 - sorted_list = [dat for dat in res["data"]["list"] if dat["available"]==1]  
52 - sorted_list.extend([dat for dat in res["data"]["list"] if dat["available"] == -1])  
53 - res["data"]["list"] = sorted_list  
54 - res["result"]=True  
55 - except Exception as e:  
56 - raise e  
57 - return res  
58 -  
59 -  
60 -  
61 - api_doc={  
62 - "tags":["数据库接口"],  
63 - "parameters":[  
64 - {"name": "page_index",  
65 - "in": "formData",  
66 - "type": "int",  
67 - "default": "0"},  
68 - {"name": "page_size",  
69 - "in": "formData",  
70 - "type": "int",  
71 - "default": "10"},  
72 - {"name": "alias",  
73 - "in": "formData",  
74 - "type": "string","description":"数据库别名"},  
75 - {"name": "guid",  
76 - "in": "formData",  
77 - "type": "string", "description": "数据库guid"}  
78 - ],  
79 - "responses":{  
80 - 200:{  
81 - "schema":{  
82 - "properties":{  
83 - }  
84 - }  
85 - }  
86 - }  
87 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +from app.models import Database,DES
  6 +from contextlib import closing
  7 +from sqlalchemy import create_engine
  8 +
  9 +from app.models import Database
  10 +
  11 +
  12 +from app.util.component.ApiTemplate import ApiTemplate
  13 +from app.util.component.ModelVisitor import ModelVisitor
  14 +class Api(ApiTemplate):
  15 + api_name = "获取数据库列表"
  16 + def process(self):
  17 + res = {}
  18 + res["data"]={}
  19 + try:
  20 + page_index = int(self.para.get("pageIndex", "0"))
  21 + page_size = int(self.para.get("pageSize", "10"))
  22 + alias = self.para.get("alias")
  23 + database_guid = self.para.get("guid")
  24 + database = Database.query.order_by(Database.create_time.desc())
  25 +
  26 + if alias:
  27 + database = database.filter(Database.alias.like("%" + alias + "%"))
  28 + if database_guid:
  29 + database = database.filter_by(guid = database_guid)
  30 +
  31 + res["data"]["count"] = database.count()
  32 +
  33 + database = database.limit(page_size).offset(page_index * page_size).all()
  34 + res["data"]["list"] =[]
  35 + for datab in database:
  36 + # 测试连接
  37 + try:
  38 + engine = create_engine(DES.decode(datab.sqlalchemy_uri), connect_args={'connect_timeout': 1})
  39 + with closing(engine.connect()):
  40 + pass
  41 + available=1
  42 + except:
  43 + available=-1
  44 + table_count = datab.relate_tables.count()
  45 + datab_json = ModelVisitor.database_to_json(datab)
  46 + datab_json["table_count"] = table_count
  47 + datab_json["available"] = available
  48 + res["data"]["list"].append(datab_json)
  49 +
  50 + # 可用非可用排序
  51 + sorted_list = [dat for dat in res["data"]["list"] if dat["available"]==1]
  52 + sorted_list.extend([dat for dat in res["data"]["list"] if dat["available"] == -1])
  53 + res["data"]["list"] = sorted_list
  54 + res["result"]=True
  55 + except Exception as e:
  56 + raise e
  57 + return res
  58 +
  59 +
  60 +
  61 + api_doc={
  62 + "tags":["数据库接口"],
  63 + "parameters":[
  64 + {"name": "page_index",
  65 + "in": "formData",
  66 + "type": "int",
  67 + "default": "0"},
  68 + {"name": "page_size",
  69 + "in": "formData",
  70 + "type": "int",
  71 + "default": "10"},
  72 + {"name": "alias",
  73 + "in": "formData",
  74 + "type": "string","description":"数据库别名"},
  75 + {"name": "guid",
  76 + "in": "formData",
  77 + "type": "string", "description": "数据库guid"}
  78 + ],
  79 + "responses":{
  80 + 200:{
  81 + "schema":{
  82 + "properties":{
  83 + }
  84 + }
  85 + }
  86 + }
  87 + }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/9  
4 -#email: nheweijun@sina.com  
5 -import datetime  
6 -from app.models import Database,db,DES,Table,Columns,TableVacuate  
7 -# from app.util import get_db_session,get_info_from_sqlachemy_uri  
8 -import uuid  
9 -from . import database_test  
10 -# from app.util import open_pg_data_source  
11 -from osgeo.ogr import DataSource,Layer,FeatureDefn,FieldDefn,Feature  
12 -from sqlalchemy.orm import Session  
13 -from sqlalchemy import create_engine  
14 -from sqlalchemy.orm import sessionmaker  
15 -from app.util.component.ApiTemplate import ApiTemplate  
16 -from app.util.component.PGUtil import PGUtil  
17 -from app.util.component.GeometryAdapter import GeometryAdapter  
18 -class Api(ApiTemplate):  
19 - api_name = "数据库注册"  
20 - def process(self):  
21 - res ={}  
22 - res["result"] = False  
23 - try:  
24 - host = self.para.get("host")  
25 - port = self.para.get("port")  
26 - user = self.para.get("user")  
27 - passwd = self.para.get("passwd")  
28 - database = self.para.get("database")  
29 - encryption = int(self.para.get("encryption","0"))  
30 - if encryption:  
31 - passwd = DES.decode(passwd)  
32 -  
33 - sqlalchemy_uri = "postgresql://{}:{}@{}:{}/{}".format(user,passwd,host,port,database)  
34 - connectsrt = "hostaddr={} port={} dbname='{}' user='{}' password='{}'".format(host,port,database,user,passwd)  
35 -  
36 - #测试连接  
37 - test = database_test.Api().result  
38 -  
39 - if not test["result"]:  
40 - return test  
41 -  
42 - #判断数据库是否存在  
43 - database = db.session.query(Database).filter_by(alias=self.para.get("alias")).one_or_none()  
44 -  
45 - #真实的数据库  
46 - real_database = db.session.query(Database).filter_by(connectstr=DES.encode(connectsrt)).all()  
47 -  
48 - if database:  
49 - res["msg"] = "数据库已存在,请修改别名!"  
50 - return res  
51 -  
52 - elif real_database:  
53 - res["msg"] = "数据库连接已存在,请修改数据库连接!"  
54 - return res  
55 - elif not self.check_space(sqlalchemy_uri):  
56 - res["msg"] = "数据不是空间数据库!"  
57 - return res  
58 -  
59 - else:  
60 - this_time = datetime.datetime.now()  
61 - database_guid = uuid.uuid1().__str__()  
62 -  
63 - db_tuple = PGUtil.get_info_from_sqlachemy_uri(sqlalchemy_uri)  
64 -  
65 - database = Database(guid= database_guid,  
66 - name = db_tuple[4],  
67 - alias=self.para.get("alias"),  
68 - sqlalchemy_uri=DES.encode(sqlalchemy_uri),  
69 - description=self.para.get("description"),  
70 - creator=self.para.get("creator"),  
71 - create_time=this_time,  
72 - update_time=this_time,  
73 - connectstr=DES.encode(connectsrt))  
74 - db.session.add(database)  
75 -  
76 - # 将该库中的数据都注册进来  
77 - self.register_table(database)  
78 - db.session.commit()  
79 - res["msg"] = "注册成功!"  
80 - res["result"]=True  
81 - res["data"] = database_guid  
82 - except Exception as e:  
83 - db.session.rollback()  
84 - raise e  
85 - return res  
86 -  
87 -  
88 - def register_table(self,database):  
89 - this_time = datetime.datetime.now()  
90 - pg_ds: DataSource = PGUtil.open_pg_data_source(1, DES.decode(database.sqlalchemy_uri))  
91 -  
92 - # 注册空间表  
93 - spatial_table_name,tables = self.register_spatial_table(pg_ds, database, this_time)  
94 -  
95 - #注册抽稀表  
96 - self.regiser_vacuate_talbe(pg_ds,tables)  
97 -  
98 - #注册普通表  
99 - self.register_common_table(this_time,database,spatial_table_name)  
100 -  
101 - pg_ds.Destroy()  
102 -  
103 -  
104 - def register_spatial_table(self,pg_ds,database,this_time):  
105 - spatial_table_name =[]  
106 - tables=[]  
107 - for i in range(pg_ds.GetLayerCount()):  
108 - layer: Layer = pg_ds.GetLayer(i)  
109 - l_name = layer.GetName()  
110 - # 只注册public的空间表,其他表空间的表名会有.  
111 - if layer.GetName().__contains__("."):  
112 - continue  
113 -  
114 - # 不注册抽稀表  
115 - if layer.GetName().__contains__("_vacuate_"):  
116 - spatial_table_name.append(layer.GetName())  
117 - continue  
118 -  
119 - # 范围统计和数量统计以100w为界限  
120 - query_count_layer: Layer = pg_ds.ExecuteSQL(  
121 - "SELECT reltuples::bigint AS ec FROM pg_class WHERE oid = 'public.{}'::regclass".format(l_name))  
122 - feature_count = query_count_layer.GetFeature(0).GetField("ec")  
123 - # 要素少于100w可以精确统计  
124 - if feature_count < 1000000:  
125 - feature_count = layer.GetFeatureCount()  
126 - ext = layer.GetExtent()  
127 - else:  
128 - query_ext_layer: Layer = pg_ds.ExecuteSQL(  
129 - "select geometry(ST_EstimatedExtent('public', '{}','{}'))".format(l_name,  
130 - layer.GetGeometryColumn()))  
131 - ext = query_ext_layer.GetExtent()  
132 - if ext[0] < 360:  
133 - ext = [round(e, 6) for e in ext]  
134 - else:  
135 - ext = [round(e, 2) for e in ext]  
136 - extent = "{},{},{},{}".format(ext[0], ext[1], ext[2], ext[3])  
137 -  
138 - table_guid = uuid.uuid1().__str__()  
139 -  
140 - table = Table(guid=table_guid,  
141 - database_guid=database.guid,  
142 - # alias=layer.GetName(),  
143 - name=layer.GetName(), create_time=this_time, update_time=this_time,  
144 - table_type=GeometryAdapter.get_table_type(layer.GetGeomType()),  
145 - extent=extent,  
146 - feature_count=feature_count  
147 - )  
148 -  
149 - db.session.add(table)  
150 - tables.append(table)  
151 -  
152 - feature_defn: FeatureDefn = layer.GetLayerDefn()  
153 -  
154 - for i in range(feature_defn.GetFieldCount()):  
155 - field_defn: FieldDefn = feature_defn.GetFieldDefn(i)  
156 - field_name = field_defn.GetName().lower()  
157 - field_alias = field_name if field_defn.GetAlternativeName() is None or field_defn.GetAlternativeName().__eq__(  
158 - "") else field_defn.GetAlternativeName()  
159 - column = Columns(guid=uuid.uuid1().__str__(), table_guid=table_guid,  
160 - name=field_name, alias=field_alias, create_time=this_time, update_time=this_time)  
161 - db.session.add(column)  
162 -  
163 - spatial_table_name.append(layer.GetName())  
164 - return spatial_table_name,tables  
165 -  
166 -  
167 - def register_common_table(self,this_time,database,spatial_table_name):  
168 - # 注册普通表  
169 - db_session: Session = PGUtil.get_db_session(DES.decode(database.sqlalchemy_uri))  
170 -  
171 - # 只注册public中的表  
172 - result = db_session.execute(  
173 - "select relname as tabname from pg_class c where relkind = 'r' and relnamespace=2200 and relname not like 'pg_%' and relname not like 'sql_%' order by relname").fetchall()  
174 - for re in result:  
175 - table_name = re[0]  
176 - if table_name not in spatial_table_name:  
177 -  
178 - table_guid = uuid.uuid1().__str__()  
179 - count = db_session.execute('select count(*) from "{}"'.format(table_name)).fetchone()[0]  
180 -  
181 - table = Table(guid=table_guid,  
182 - database_guid=database.guid,  
183 - # alias=layer.GetName(),  
184 - name=table_name, create_time=this_time, update_time=this_time,  
185 - table_type=0,  
186 - feature_count=count  
187 - )  
188 -  
189 - db.session.add(table)  
190 -  
191 - sql = '''  
192 - SELECT  
193 - a.attnum,  
194 - a.attname AS field  
195 - FROM  
196 - pg_class c,  
197 - pg_attribute a,  
198 - pg_type t  
199 - WHERE  
200 - c.relname = '{}'  
201 - and a.attnum > 0  
202 - and a.attrelid = c.oid  
203 - and a.atttypid = t.oid  
204 - ORDER BY a.attnum  
205 - '''.format(table_name)  
206 -  
207 - cols = db_session.execute(sql).fetchall()  
208 - for col in cols:  
209 - column = Columns(guid=uuid.uuid1().__str__(), table_guid=table_guid,  
210 - name=col[1], create_time=this_time, update_time=this_time)  
211 - db.session.add(column)  
212 - db_session.close()  
213 -  
214 - def regiser_vacuate_talbe(self,pg_ds,tables):  
215 -  
216 - # 注册抽稀表  
217 - for i in range(pg_ds.GetLayerCount()):  
218 - layer:Layer = pg_ds.GetLayer(i)  
219 - l_name = layer.GetName()  
220 - if l_name.__contains__("_vacuate_"):  
221 - base_layer_name=l_name.split("_vacuate_")[0]  
222 - level = l_name.split("_")[-2]  
223 - pixel_distance_str: str ="0"  
224 - try:  
225 - pixel_distance_str :str= l_name.split("_")[-1]  
226 - if pixel_distance_str.startswith("0"):  
227 - pixel_distance_str="0.{}".format(pixel_distance_str)  
228 - except:  
229 - pass  
230 - base_table = [table for table in tables if table.name.__eq__(base_layer_name)][0]  
231 - table_vacuate = TableVacuate(guid=uuid.uuid1().__str__(),  
232 - table_guid=base_table.guid,  
233 - level=level,  
234 - name=l_name,  
235 - pixel_distance=float(pixel_distance_str))  
236 - db.session.add(table_vacuate)  
237 -  
238 -  
239 -  
240 - def check_space(self,sqlachemy_uri):  
241 - system_session = None  
242 - check = True  
243 - try:  
244 - test_sql = "select st_geometryfromtext('POINT(1 1)')"  
245 - engine = create_engine(sqlachemy_uri)  
246 - system_session = sessionmaker(bind=engine)()  
247 - system_session.execute(test_sql).fetchone()  
248 -  
249 - except:  
250 - check = False  
251 - finally:  
252 - if system_session:  
253 - system_session.close()  
254 -  
255 - return check  
256 -  
257 - api_doc={  
258 - "tags":["数据库接口"],  
259 - "parameters":[  
260 - {"name": "host",  
261 - "in": "formData",  
262 - "type": "string", "required": "true"},  
263 - {"name": "port",  
264 - "in": "formData",  
265 - "type": "string", "required": "true"},  
266 - {"name": "user",  
267 - "in": "formData",  
268 - "type": "string", "required": "true"},  
269 - {"name": "passwd",  
270 - "in": "formData",  
271 - "type": "string", "required": "true"},  
272 - {"name": "database",  
273 - "in": "formData",  
274 - "type": "string", "required": "true"},  
275 - {"name": "creator",  
276 - "in": "formData",  
277 - "type": "string", "required": "true"},  
278 -  
279 - {"name": "alias",  
280 - "in": "formData",  
281 - "type": "string","description":"数据库别名","required": "true"},  
282 -  
283 - {"name": "encryption",  
284 - "in": "formData",  
285 - "type": "integer", "description": "密码是否加密", "enum": [0,1]},  
286 - ],  
287 - "responses":{  
288 - 200:{  
289 - "schema":{  
290 - "properties":{  
291 - }  
292 - }  
293 - }  
294 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/9
  4 +#email: nheweijun@sina.com
  5 +import datetime
  6 +from app.models import Database,db,DES,Table,Columns,TableVacuate
  7 +# from app.util import get_db_session,get_info_from_sqlachemy_uri
  8 +import uuid
  9 +from . import database_test
  10 +# from app.util import open_pg_data_source
  11 +from osgeo.ogr import DataSource,Layer,FeatureDefn,FieldDefn,Feature
  12 +from sqlalchemy.orm import Session
  13 +from sqlalchemy import create_engine
  14 +from sqlalchemy.orm import sessionmaker
  15 +from app.util.component.ApiTemplate import ApiTemplate
  16 +from app.util.component.PGUtil import PGUtil
  17 +from app.util.component.GeometryAdapter import GeometryAdapter
  18 +class Api(ApiTemplate):
  19 + api_name = "数据库注册"
  20 + def process(self):
  21 + res ={}
  22 + res["result"] = False
  23 + try:
  24 + host = self.para.get("host")
  25 + port = self.para.get("port")
  26 + user = self.para.get("user")
  27 + passwd = self.para.get("passwd")
  28 + database = self.para.get("database")
  29 + encryption = int(self.para.get("encryption","0"))
  30 + if encryption:
  31 + passwd = DES.decode(passwd)
  32 +
  33 + sqlalchemy_uri = "postgresql://{}:{}@{}:{}/{}".format(user,passwd,host,port,database)
  34 + connectsrt = "hostaddr={} port={} dbname='{}' user='{}' password='{}'".format(host,port,database,user,passwd)
  35 +
  36 + #测试连接
  37 + test = database_test.Api().result
  38 +
  39 + if not test["result"]:
  40 + return test
  41 +
  42 + #判断数据库是否存在
  43 + database = db.session.query(Database).filter_by(alias=self.para.get("alias")).one_or_none()
  44 +
  45 + #真实的数据库
  46 + real_database = db.session.query(Database).filter_by(connectstr=DES.encode(connectsrt)).all()
  47 +
  48 + if database:
  49 + res["msg"] = "数据库已存在,请修改别名!"
  50 + return res
  51 +
  52 + elif real_database:
  53 + res["msg"] = "数据库连接已存在,请修改数据库连接!"
  54 + return res
  55 + elif not self.check_space(sqlalchemy_uri):
  56 + res["msg"] = "数据不是空间数据库!"
  57 + return res
  58 +
  59 + else:
  60 + this_time = datetime.datetime.now()
  61 + database_guid = uuid.uuid1().__str__()
  62 +
  63 + db_tuple = PGUtil.get_info_from_sqlachemy_uri(sqlalchemy_uri)
  64 +
  65 + database = Database(guid= database_guid,
  66 + name = db_tuple[4],
  67 + alias=self.para.get("alias"),
  68 + sqlalchemy_uri=DES.encode(sqlalchemy_uri),
  69 + description=self.para.get("description"),
  70 + creator=self.para.get("creator"),
  71 + create_time=this_time,
  72 + update_time=this_time,
  73 + connectstr=DES.encode(connectsrt))
  74 + db.session.add(database)
  75 +
  76 + # 将该库中的数据都注册进来
  77 + self.register_table(database)
  78 + db.session.commit()
  79 + res["msg"] = "注册成功!"
  80 + res["result"]=True
  81 + res["data"] = database_guid
  82 + except Exception as e:
  83 + db.session.rollback()
  84 + raise e
  85 + return res
  86 +
  87 +
  88 + def register_table(self,database):
  89 + this_time = datetime.datetime.now()
  90 + pg_ds: DataSource = PGUtil.open_pg_data_source(1, DES.decode(database.sqlalchemy_uri))
  91 +
  92 + # 注册空间表
  93 + spatial_table_name,tables = self.register_spatial_table(pg_ds, database, this_time)
  94 +
  95 + #注册抽稀表
  96 + self.regiser_vacuate_talbe(pg_ds,tables)
  97 +
  98 + #注册普通表
  99 + self.register_common_table(this_time,database,spatial_table_name)
  100 +
  101 + pg_ds.Destroy()
  102 +
  103 +
  104 + def register_spatial_table(self,pg_ds,database,this_time):
  105 + spatial_table_name =[]
  106 + tables=[]
  107 + for i in range(pg_ds.GetLayerCount()):
  108 + layer: Layer = pg_ds.GetLayer(i)
  109 + l_name = layer.GetName()
  110 + # 只注册public的空间表,其他表空间的表名会有.
  111 + if layer.GetName().__contains__("."):
  112 + continue
  113 +
  114 + # 不注册抽稀表
  115 + if layer.GetName().__contains__("_vacuate_"):
  116 + spatial_table_name.append(layer.GetName())
  117 + continue
  118 +
  119 + # 范围统计和数量统计以100w为界限
  120 + query_count_layer: Layer = pg_ds.ExecuteSQL(
  121 + "SELECT reltuples::bigint AS ec FROM pg_class WHERE oid = 'public.{}'::regclass".format(l_name))
  122 + feature_count = query_count_layer.GetFeature(0).GetField("ec")
  123 + # 要素少于100w可以精确统计
  124 + if feature_count < 1000000:
  125 + feature_count = layer.GetFeatureCount()
  126 + ext = layer.GetExtent()
  127 + else:
  128 + query_ext_layer: Layer = pg_ds.ExecuteSQL(
  129 + "select geometry(ST_EstimatedExtent('public', '{}','{}'))".format(l_name,
  130 + layer.GetGeometryColumn()))
  131 + ext = query_ext_layer.GetExtent()
  132 + if ext[0] < 360:
  133 + ext = [round(e, 6) for e in ext]
  134 + else:
  135 + ext = [round(e, 2) for e in ext]
  136 + extent = "{},{},{},{}".format(ext[0], ext[1], ext[2], ext[3])
  137 +
  138 + table_guid = uuid.uuid1().__str__()
  139 +
  140 + table = Table(guid=table_guid,
  141 + database_guid=database.guid,
  142 + # alias=layer.GetName(),
  143 + name=layer.GetName(), create_time=this_time, update_time=this_time,
  144 + table_type=GeometryAdapter.get_table_type(layer.GetGeomType()),
  145 + extent=extent,
  146 + feature_count=feature_count
  147 + )
  148 +
  149 + db.session.add(table)
  150 + tables.append(table)
  151 +
  152 + feature_defn: FeatureDefn = layer.GetLayerDefn()
  153 +
  154 + for i in range(feature_defn.GetFieldCount()):
  155 + field_defn: FieldDefn = feature_defn.GetFieldDefn(i)
  156 + field_name = field_defn.GetName().lower()
  157 + field_alias = field_name if field_defn.GetAlternativeName() is None or field_defn.GetAlternativeName().__eq__(
  158 + "") else field_defn.GetAlternativeName()
  159 + column = Columns(guid=uuid.uuid1().__str__(), table_guid=table_guid,
  160 + name=field_name, alias=field_alias, create_time=this_time, update_time=this_time)
  161 + db.session.add(column)
  162 +
  163 + spatial_table_name.append(layer.GetName())
  164 + return spatial_table_name,tables
  165 +
  166 +
  167 + def register_common_table(self,this_time,database,spatial_table_name):
  168 + # 注册普通表
  169 + db_session: Session = PGUtil.get_db_session(DES.decode(database.sqlalchemy_uri))
  170 +
  171 + # 只注册public中的表
  172 + result = db_session.execute(
  173 + "select relname as tabname from pg_class c where relkind = 'r' and relnamespace=2200 and relname not like 'pg_%' and relname not like 'sql_%' order by relname").fetchall()
  174 + for re in result:
  175 + table_name = re[0]
  176 + if table_name not in spatial_table_name:
  177 +
  178 + table_guid = uuid.uuid1().__str__()
  179 + count = db_session.execute('select count(*) from "{}"'.format(table_name)).fetchone()[0]
  180 +
  181 + table = Table(guid=table_guid,
  182 + database_guid=database.guid,
  183 + # alias=layer.GetName(),
  184 + name=table_name, create_time=this_time, update_time=this_time,
  185 + table_type=0,
  186 + feature_count=count
  187 + )
  188 +
  189 + db.session.add(table)
  190 +
  191 + sql = '''
  192 + SELECT
  193 + a.attnum,
  194 + a.attname AS field
  195 + FROM
  196 + pg_class c,
  197 + pg_attribute a,
  198 + pg_type t
  199 + WHERE
  200 + c.relname = '{}'
  201 + and a.attnum > 0
  202 + and a.attrelid = c.oid
  203 + and a.atttypid = t.oid
  204 + ORDER BY a.attnum
  205 + '''.format(table_name)
  206 +
  207 + cols = db_session.execute(sql).fetchall()
  208 + for col in cols:
  209 + column = Columns(guid=uuid.uuid1().__str__(), table_guid=table_guid,
  210 + name=col[1], create_time=this_time, update_time=this_time)
  211 + db.session.add(column)
  212 + db_session.close()
  213 +
  214 + def regiser_vacuate_talbe(self,pg_ds,tables):
  215 +
  216 + # 注册抽稀表
  217 + for i in range(pg_ds.GetLayerCount()):
  218 + layer:Layer = pg_ds.GetLayer(i)
  219 + l_name = layer.GetName()
  220 + if l_name.__contains__("_vacuate_"):
  221 + base_layer_name=l_name.split("_vacuate_")[0]
  222 + level = l_name.split("_")[-2]
  223 + pixel_distance_str: str ="0"
  224 + try:
  225 + pixel_distance_str :str= l_name.split("_")[-1]
  226 + if pixel_distance_str.startswith("0"):
  227 + pixel_distance_str="0.{}".format(pixel_distance_str)
  228 + except:
  229 + pass
  230 + base_table = [table for table in tables if table.name.__eq__(base_layer_name)][0]
  231 + table_vacuate = TableVacuate(guid=uuid.uuid1().__str__(),
  232 + table_guid=base_table.guid,
  233 + level=level,
  234 + name=l_name,
  235 + pixel_distance=float(pixel_distance_str))
  236 +
  237 + Table.query.filter_by(guid=base_table.guid).update({"is_vacuate": 1})
  238 + db.session.add(table_vacuate)
  239 +
  240 +
  241 +
  242 + def check_space(self,sqlachemy_uri):
  243 + system_session = None
  244 + check = True
  245 + try:
  246 + test_sql = "select st_geometryfromtext('POINT(1 1)')"
  247 + engine = create_engine(sqlachemy_uri)
  248 + system_session = sessionmaker(bind=engine)()
  249 + system_session.execute(test_sql).fetchone()
  250 +
  251 + except:
  252 + check = False
  253 + finally:
  254 + if system_session:
  255 + system_session.close()
  256 +
  257 + return check
  258 +
  259 + api_doc={
  260 + "tags":["数据库接口"],
  261 + "parameters":[
  262 + {"name": "host",
  263 + "in": "formData",
  264 + "type": "string", "required": "true"},
  265 + {"name": "port",
  266 + "in": "formData",
  267 + "type": "string", "required": "true"},
  268 + {"name": "user",
  269 + "in": "formData",
  270 + "type": "string", "required": "true"},
  271 + {"name": "passwd",
  272 + "in": "formData",
  273 + "type": "string", "required": "true"},
  274 + {"name": "database",
  275 + "in": "formData",
  276 + "type": "string", "required": "true"},
  277 + {"name": "creator",
  278 + "in": "formData",
  279 + "type": "string", "required": "true"},
  280 +
  281 + {"name": "alias",
  282 + "in": "formData",
  283 + "type": "string","description":"数据库别名","required": "true"},
  284 +
  285 + {"name": "encryption",
  286 + "in": "formData",
  287 + "type": "integer", "description": "密码是否加密", "enum": [0,1]},
  288 + ],
  289 + "responses":{
  290 + 200:{
  291 + "schema":{
  292 + "properties":{
  293 + }
  294 + }
  295 + }
  296 + }
295 } 297 }
1 -# coding=utf-8  
2 -# author: 4N  
3 -# createtime: 2020/6/22  
4 -# email: nheweijun@sina.com  
5 -from contextlib import closing  
6 -  
7 -from sqlalchemy import create_engine  
8 -  
9 -from app.models import DES,Database,db  
10 -  
11 -from sqlalchemy.orm import sessionmaker  
12 -from app.util.component.ApiTemplate import ApiTemplate  
13 -class Api(ApiTemplate):  
14 - api_name = "数据库连接测试"  
15 - def process(self):  
16 - res = {}  
17 - res["result"] = False  
18 - try:  
19 -  
20 -  
21 - host = self.para.get("host")  
22 - port = self.para.get("port")  
23 - user = self.para.get("user")  
24 - passwd = self.para.get("passwd")  
25 - database = self.para.get("database")  
26 -  
27 - encryption = int(self.para.get("encryption", "0"))  
28 - if encryption:  
29 - passwd = DES.decode(passwd)  
30 -  
31 -  
32 - sqlalchemy_uri = "postgresql://{}:{}@{}:{}/{}".format(user,passwd,host,port,database)  
33 -  
34 - # if is_encrypt == "1":  
35 - # sqlalchemy_uri=DES.decode(sqlalchemy_uri)  
36 -  
37 - engine = create_engine(sqlalchemy_uri, connect_args={'connect_timeout': 2})  
38 - with closing(engine.connect()):  
39 - pass  
40 -  
41 -  
42 - #判断数据库是否存在  
43 - datab = db.session.query(Database).filter_by(alias=self.para.get("alias")).one_or_none()  
44 - #真实的数据库  
45 - connectsrt = "hostaddr={} port={} dbname='{}' user='{}' password='{}'".format(host, port, database, user,  
46 - passwd)  
47 - real_database = db.session.query(Database).filter_by(connectstr=DES.encode(connectsrt)).all()  
48 -  
49 - if datab:  
50 - res["msg"] = "数据库已存在,请修改别名!"  
51 - return res  
52 -  
53 - elif real_database:  
54 - res["msg"] = "数据库连接已存在,请修改数据库连接!"  
55 - return res  
56 -  
57 - elif not self.check_space(sqlalchemy_uri):  
58 - res["msg"] = "数据不是空间数据库!"  
59 - return res  
60 - else:  
61 - res["result"] = True  
62 - res["msg"] = "测试连接成功"  
63 - except:  
64 - raise Exception("测试连接失败!")  
65 - return res  
66 -  
67 -  
68 - def check_space(self,sqlachemy_uri):  
69 - system_session = None  
70 - check = True  
71 - try:  
72 - test_sql = "select st_geometryfromtext('POINT(1 1)')"  
73 - engine = create_engine(sqlachemy_uri)  
74 - system_session = sessionmaker(bind=engine)()  
75 - system_session.execute(test_sql).fetchone()  
76 - except:  
77 - check = False  
78 - finally:  
79 - if system_session:  
80 - system_session.close()  
81 -  
82 - return check  
83 -  
84 - api_doc={  
85 - "tags":["数据库接口"],  
86 - "parameters":[  
87 - # {"name": "sqlalchemy_uri",  
88 - # "in": "formData",  
89 - # "type": "string","description":"数据库uri","required": "true"},  
90 - {"name": "host",  
91 - "in": "formData",  
92 - "type": "string", "required": "true"},  
93 - {"name": "port",  
94 - "in": "formData",  
95 - "type": "string", "required": "true"},  
96 - {"name": "user",  
97 - "in": "formData",  
98 - "type": "string", "required": "true"},  
99 - {"name": "passwd",  
100 - "in": "formData",  
101 - "type": "string", "required": "true"},  
102 - {"name": "database",  
103 - "in": "formData",  
104 - "type": "string", "required": "true"},  
105 - # {"name": "alias",  
106 - # "in": "formData",  
107 - # "type": "string", "required": "true"},  
108 - {"name": "encryption",  
109 - "in": "formData",  
110 - "type": "int", "description": "密码是否加密", "enum": [0, 1]},  
111 -  
112 - ],  
113 - "responses":{  
114 - 200:{  
115 - "schema":{  
116 - "properties":{  
117 - }  
118 - }  
119 - }  
120 - } 1 +# coding=utf-8
  2 +# author: 4N
  3 +# createtime: 2020/6/22
  4 +# email: nheweijun@sina.com
  5 +from contextlib import closing
  6 +
  7 +from sqlalchemy import create_engine
  8 +
  9 +from app.models import DES,Database,db
  10 +
  11 +from sqlalchemy.orm import sessionmaker
  12 +from app.util.component.ApiTemplate import ApiTemplate
  13 +class Api(ApiTemplate):
  14 + api_name = "数据库连接测试"
  15 + def process(self):
  16 + res = {}
  17 + res["result"] = False
  18 + try:
  19 +
  20 +
  21 + host = self.para.get("host")
  22 + port = self.para.get("port")
  23 + user = self.para.get("user")
  24 + passwd = self.para.get("passwd")
  25 + database = self.para.get("database")
  26 +
  27 + encryption = int(self.para.get("encryption", "0"))
  28 + if encryption:
  29 + passwd = DES.decode(passwd)
  30 +
  31 +
  32 + sqlalchemy_uri = "postgresql://{}:{}@{}:{}/{}".format(user,passwd,host,port,database)
  33 +
  34 + # if is_encrypt == "1":
  35 + # sqlalchemy_uri=DES.decode(sqlalchemy_uri)
  36 +
  37 + engine = create_engine(sqlalchemy_uri, connect_args={'connect_timeout': 2})
  38 + with closing(engine.connect()):
  39 + pass
  40 +
  41 +
  42 + #判断数据库是否存在
  43 + datab = db.session.query(Database).filter_by(alias=self.para.get("alias")).one_or_none()
  44 + #真实的数据库
  45 + connectsrt = "hostaddr={} port={} dbname='{}' user='{}' password='{}'".format(host, port, database, user,
  46 + passwd)
  47 + real_database = db.session.query(Database).filter_by(connectstr=DES.encode(connectsrt)).all()
  48 +
  49 + if datab:
  50 + res["msg"] = "数据库已存在,请修改别名!"
  51 + return res
  52 +
  53 + elif real_database:
  54 + res["msg"] = "数据库连接已存在,请修改数据库连接!"
  55 + return res
  56 +
  57 + elif not self.check_space(sqlalchemy_uri):
  58 + res["msg"] = "数据不是空间数据库!"
  59 + return res
  60 + else:
  61 + res["result"] = True
  62 + res["msg"] = "测试连接成功"
  63 + except:
  64 + raise Exception("测试连接失败!")
  65 + return res
  66 +
  67 +
  68 + def check_space(self,sqlachemy_uri):
  69 + system_session = None
  70 + check = True
  71 + try:
  72 + test_sql = "select st_geometryfromtext('POINT(1 1)')"
  73 + engine = create_engine(sqlachemy_uri)
  74 + system_session = sessionmaker(bind=engine)()
  75 + system_session.execute(test_sql).fetchone()
  76 + except:
  77 + check = False
  78 + finally:
  79 + if system_session:
  80 + system_session.close()
  81 +
  82 + return check
  83 +
  84 + api_doc={
  85 + "tags":["数据库接口"],
  86 + "parameters":[
  87 + # {"name": "sqlalchemy_uri",
  88 + # "in": "formData",
  89 + # "type": "string","description":"数据库uri","required": "true"},
  90 + {"name": "host",
  91 + "in": "formData",
  92 + "type": "string", "required": "true"},
  93 + {"name": "port",
  94 + "in": "formData",
  95 + "type": "string", "required": "true"},
  96 + {"name": "user",
  97 + "in": "formData",
  98 + "type": "string", "required": "true"},
  99 + {"name": "passwd",
  100 + "in": "formData",
  101 + "type": "string", "required": "true"},
  102 + {"name": "database",
  103 + "in": "formData",
  104 + "type": "string", "required": "true"},
  105 + # {"name": "alias",
  106 + # "in": "formData",
  107 + # "type": "string", "required": "true"},
  108 + {"name": "encryption",
  109 + "in": "formData",
  110 + "type": "int", "description": "密码是否加密", "enum": [0, 1]},
  111 +
  112 + ],
  113 + "responses":{
  114 + 200:{
  115 + "schema":{
  116 + "properties":{
  117 + }
  118 + }
  119 + }
  120 + }
121 } 121 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/2/23  
4 -#email: nheweijun@sina.com  
5 -  
6 -from flask import Blueprint  
7 -from app.util import BlueprintApi  
8 -from flasgger import swag_from  
9 -from . import index  
10 -from . import release  
11 -from . import get_app_name  
12 -class Template(BlueprintApi):  
13 -  
14 - bp = Blueprint("Index", __name__, url_prefix="/")  
15 -  
16 - @staticmethod  
17 - @bp.route('/', methods=['GET'])  
18 - @swag_from(index.Api.api_doc)  
19 - def api_index():  
20 - """  
21 - Index接口  
22 - """  
23 - return index.Api().result  
24 -  
25 - @staticmethod  
26 - @bp.route('/release', methods=['GET'])  
27 - @swag_from(release.Api.api_doc)  
28 - def release():  
29 - """  
30 - release接口  
31 - """  
32 - return release.Api().result  
33 -  
34 - @staticmethod  
35 - @bp.route('/GetAppName', methods=['GET'])  
36 - @swag_from(get_app_name.Api.api_doc)  
37 - def get_app_name():  
38 - """  
39 - GetAppName接口  
40 - """ 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/2/23
  4 +#email: nheweijun@sina.com
  5 +
  6 +from flask import Blueprint
  7 +from app.util import BlueprintApi
  8 +from flasgger import swag_from
  9 +from . import index
  10 +from . import release
  11 +from . import get_app_name
  12 +class Template(BlueprintApi):
  13 +
  14 + bp = Blueprint("Index", __name__, url_prefix="/")
  15 +
  16 + @staticmethod
  17 + @bp.route('/', methods=['GET'])
  18 + @swag_from(index.Api.api_doc)
  19 + def api_index():
  20 + """
  21 + Index接口
  22 + """
  23 + return index.Api().result
  24 +
  25 + @staticmethod
  26 + @bp.route('/release', methods=['GET'])
  27 + @swag_from(release.Api.api_doc)
  28 + def release():
  29 + """
  30 + release接口
  31 + """
  32 + return release.Api().result
  33 +
  34 + @staticmethod
  35 + @bp.route('/GetAppName', methods=['GET'])
  36 + @swag_from(get_app_name.Api.api_doc)
  37 + def get_app_name():
  38 + """
  39 + GetAppName接口
  40 + """
41 return get_app_name.Api().result 41 return get_app_name.Api().result
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/7/20  
4 -#email: nheweijun@sina.com  
5 -  
6 -import hashlib  
7 -from flask import current_app as app  
8 -import socket  
9 -import configure  
10 -  
11 -from app.util.component.ApiTemplate import ApiTemplate  
12 -class Api(ApiTemplate):  
13 -  
14 - def process(self):  
15 - return configure.application_name  
16 -  
17 - api_doc={  
18 - "tags":["Index接口"],  
19 - "description":"Index接口",  
20 - "parameters":[  
21 - ],  
22 - "responses":{  
23 - 200:{  
24 - "schema":{  
25 - "properties":{  
26 - "content":{  
27 - "type": "string",  
28 - "description": "The name of the user"  
29 - }  
30 - }  
31 - }  
32 - }  
33 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/7/20
  4 +#email: nheweijun@sina.com
  5 +
  6 +import hashlib
  7 +from flask import current_app as app
  8 +import socket
  9 +import configure
  10 +
  11 +from app.util.component.ApiTemplate import ApiTemplate
  12 +class Api(ApiTemplate):
  13 +
  14 + def process(self):
  15 + return configure.application_name
  16 +
  17 + api_doc={
  18 + "tags":["Index接口"],
  19 + "description":"Index接口",
  20 + "parameters":[
  21 + ],
  22 + "responses":{
  23 + 200:{
  24 + "schema":{
  25 + "properties":{
  26 + "content":{
  27 + "type": "string",
  28 + "description": "The name of the user"
  29 + }
  30 + }
  31 + }
  32 + }
  33 + }
34 } 34 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/2/23  
4 -#email: nheweijun@sina.com  
5 -import hashlib  
6 -from flask import current_app as app  
7 -import socket  
8 -  
9 -from app.util.component.ApiTemplate import ApiTemplate  
10 -class Api(ApiTemplate):  
11 -  
12 - def process(self):  
13 - return {"Name":socket.gethostname(),"Type":"DMapDMS"}  
14 -  
15 - api_doc={  
16 - "tags":["Index接口"],  
17 - "description":"Index接口",  
18 - "parameters":[  
19 - ],  
20 - "responses":{  
21 - 200:{  
22 - "schema":{  
23 - "properties":{  
24 - "content":{  
25 - "type": "string",  
26 - "description": "The name of the user"  
27 - }  
28 - }  
29 - }  
30 - }  
31 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/2/23
  4 +#email: nheweijun@sina.com
  5 +import hashlib
  6 +from flask import current_app as app
  7 +import socket
  8 +
  9 +from app.util.component.ApiTemplate import ApiTemplate
  10 +class Api(ApiTemplate):
  11 +
  12 + def process(self):
  13 + return {"Name":socket.gethostname(),"Type":"DMapDMS"}
  14 +
  15 + api_doc={
  16 + "tags":["Index接口"],
  17 + "description":"Index接口",
  18 + "parameters":[
  19 + ],
  20 + "responses":{
  21 + 200:{
  22 + "schema":{
  23 + "properties":{
  24 + "content":{
  25 + "type": "string",
  26 + "description": "The name of the user"
  27 + }
  28 + }
  29 + }
  30 + }
  31 + }
32 } 32 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/2/23  
4 -#email: nheweijun@sina.com  
5 -import hashlib  
6 -from flask import current_app as app  
7 -import socket  
8 -  
9 -from app.util.component.ApiTemplate import ApiTemplate  
10 -from app.models import Task,InsertingLayerName,db  
11 -import datetime  
12 -import traceback  
13 -from sqlalchemy import or_  
14 -class Api(ApiTemplate):  
15 -  
16 - def process(self):  
17 - try:  
18 - # 遗留任务变成失败  
19 - last_tasks = db.session.query(Task).filter(or_(Task.state == 0, Task.state == 2))  
20 - last_tasks.update({"state": -1,"process":"入库失败","update_time":datetime.datetime.now()})  
21 - last_lins = db.session.query(InsertingLayerName).all()  
22 - if last_lins:  
23 - for lin in last_lins:  
24 - db.session.delete(lin)  
25 - db.session.commit()  
26 - except Exception as e:  
27 - # print(e)  
28 - print(traceback.format_exc())  
29 -  
30 - return {"state": 1}  
31 -  
32 - api_doc={  
33 - "tags":["Index接口"],  
34 - "description":"Index接口",  
35 - "parameters":[  
36 - ],  
37 - "responses":{  
38 - 200:{  
39 - "schema":{  
40 - "properties":{  
41 - "content":{  
42 - "type": "string",  
43 - "description": "The name of the user"  
44 - }  
45 - }  
46 - }  
47 - }  
48 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/2/23
  4 +#email: nheweijun@sina.com
  5 +import hashlib
  6 +from flask import current_app as app
  7 +import socket
  8 +
  9 +from app.util.component.ApiTemplate import ApiTemplate
  10 +from app.models import Task,InsertingLayerName,db
  11 +import datetime
  12 +import traceback
  13 +from sqlalchemy import or_
  14 +class Api(ApiTemplate):
  15 +
  16 + def process(self):
  17 + try:
  18 + # 遗留任务变成失败
  19 + last_tasks = db.session.query(Task).filter(or_(Task.state == 0, Task.state == 2))
  20 + last_tasks.update({"state": -1,"process":"入库失败","update_time":datetime.datetime.now()})
  21 + last_lins = db.session.query(InsertingLayerName).all()
  22 + if last_lins:
  23 + for lin in last_lins:
  24 + db.session.delete(lin)
  25 + db.session.commit()
  26 + except Exception as e:
  27 + # print(e)
  28 + print(traceback.format_exc())
  29 +
  30 + return {"state": 1}
  31 +
  32 + api_doc={
  33 + "tags":["Index接口"],
  34 + "description":"Index接口",
  35 + "parameters":[
  36 + ],
  37 + "responses":{
  38 + 200:{
  39 + "schema":{
  40 + "properties":{
  41 + "content":{
  42 + "type": "string",
  43 + "description": "The name of the user"
  44 + }
  45 + }
  46 + }
  47 + }
  48 + }
49 } 49 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2020/12/8  
4 -#email: nheweijun@sina.com  
5 -from flasgger import swag_from  
6 -from flask import Blueprint  
7 -from app.util import BlueprintApi  
8 -  
9 -from flask import send_from_directory,current_app,send_file  
10 -import os  
11 -import shutil  
12 -from . import data_download  
13 -from . import get_meta  
14 -from . import data_entry_by_meta  
15 -from . import get_data_list  
16 -from flask import after_this_request  
17 -import time  
18 -  
19 -class DataManager(BlueprintApi):  
20 -  
21 - bp:Blueprint = Blueprint("DataTool", __name__, url_prefix="/API/IO")  
22 -  
23 -  
24 - @staticmethod  
25 - @bp.route('/Download/<file>', methods=['GET'])  
26 - def table_download_file(file):  
27 - parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  
28 - dirpath = os.path.join(parent,"file_tmp")  
29 -  
30 - # @staticmethod  
31 - # @after_this_request  
32 - # def delete(response):  
33 - # try:  
34 - # os.remove(os.path.join(dirpath,file))  
35 - # # shutil.rmtree(dirpath)  
36 - # print("删除文件成功!")  
37 - # except Exception as e:  
38 - # print(e)  
39 - # print("删除文件失败!")  
40 - # return response  
41 -  
42 - return send_from_directory(dirpath, filename=file, as_attachment=True)  
43 -  
44 - @staticmethod  
45 - @bp.route('/DeleteFile/<file>', methods=['GET'])  
46 - def d_file(file):  
47 - parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  
48 - dirpath = os.path.join(parent, "file_tmp")  
49 -  
50 - result={}  
51 - try:  
52 - os.remove(os.path.join(dirpath, file))  
53 - # shutil.rmtree(dirpath)  
54 - result["message"]="删除文件成功!"  
55 - except Exception as e:  
56 - print(e)  
57 - result["message"] ="删除文件失败!"  
58 - return result  
59 -  
60 - @staticmethod  
61 - @bp.route('/DataDownload', methods=['POST'])  
62 - @swag_from(data_download.Api.api_doc)  
63 - def table_download():  
64 - """  
65 - 下载数据  
66 - """  
67 - return data_download.Api().result  
68 -  
69 -  
70 - @staticmethod  
71 - @bp.route('/GetMeta', methods=['POST'])  
72 - @swag_from(get_meta.Api.api_doc)  
73 - def get_meta():  
74 - """  
75 - 数据Meta  
76 - """  
77 - return get_meta.Api().result  
78 -  
79 - @staticmethod  
80 - @bp.route('/GetDataList', methods=['POST'])  
81 - @swag_from(get_data_list.Api.api_doc)  
82 - def get_data_list():  
83 - """  
84 - 本地数据list  
85 - """  
86 - return get_data_list.Api().result  
87 -  
88 - @staticmethod  
89 - @bp.route('/DataEntryByMeta', methods=['POST'])  
90 - @swag_from(data_entry_by_meta.Api.api_doc)  
91 - def data_entry_by_meta():  
92 - """  
93 - 数据入库ByMeta  
94 - """ 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2020/12/8
  4 +#email: nheweijun@sina.com
  5 +from flasgger import swag_from
  6 +from flask import Blueprint
  7 +from app.util import BlueprintApi
  8 +
  9 +from flask import send_from_directory,current_app,send_file
  10 +import os
  11 +import shutil
  12 +from . import data_download
  13 +from . import get_meta
  14 +from . import data_entry_by_meta
  15 +from . import get_data_list
  16 +from flask import after_this_request
  17 +import time
  18 +
  19 +class DataManager(BlueprintApi):
  20 +
  21 + bp:Blueprint = Blueprint("DataTool", __name__, url_prefix="/API/IO")
  22 +
  23 +
  24 + @staticmethod
  25 + @bp.route('/Download/<file>', methods=['GET'])
  26 + def table_download_file(file):
  27 + parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  28 + dirpath = os.path.join(parent,"file_tmp")
  29 +
  30 + # @staticmethod
  31 + # @after_this_request
  32 + # def delete(response):
  33 + # try:
  34 + # os.remove(os.path.join(dirpath,file))
  35 + # # shutil.rmtree(dirpath)
  36 + # print("删除文件成功!")
  37 + # except Exception as e:
  38 + # print(e)
  39 + # print("删除文件失败!")
  40 + # return response
  41 +
  42 + return send_from_directory(dirpath, filename=file, as_attachment=True)
  43 +
  44 + @staticmethod
  45 + @bp.route('/DeleteFile/<file>', methods=['GET'])
  46 + def d_file(file):
  47 + parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  48 + dirpath = os.path.join(parent, "file_tmp")
  49 +
  50 + result={}
  51 + try:
  52 + os.remove(os.path.join(dirpath, file))
  53 + # shutil.rmtree(dirpath)
  54 + result["message"]="删除文件成功!"
  55 + except Exception as e:
  56 + print(e)
  57 + result["message"] ="删除文件失败!"
  58 + return result
  59 +
  60 + @staticmethod
  61 + @bp.route('/DataDownload', methods=['POST'])
  62 + @swag_from(data_download.Api.api_doc)
  63 + def table_download():
  64 + """
  65 + 下载数据
  66 + """
  67 + return data_download.Api().result
  68 +
  69 +
  70 + @staticmethod
  71 + @bp.route('/GetMeta', methods=['POST'])
  72 + @swag_from(get_meta.Api.api_doc)
  73 + def get_meta():
  74 + """
  75 + 数据Meta
  76 + """
  77 + return get_meta.Api().result
  78 +
  79 + @staticmethod
  80 + @bp.route('/GetDataList', methods=['POST'])
  81 + @swag_from(get_data_list.Api.api_doc)
  82 + def get_data_list():
  83 + """
  84 + 本地数据list
  85 + """
  86 + return get_data_list.Api().result
  87 +
  88 + @staticmethod
  89 + @bp.route('/DataEntryByMeta', methods=['POST'])
  90 + @swag_from(data_entry_by_meta.Api.api_doc)
  91 + def data_entry_by_meta():
  92 + """
  93 + 数据入库ByMeta
  94 + """
95 return data_entry_by_meta.Api().result 95 return data_entry_by_meta.Api().result
1 -# coding=utf-8  
2 -# author: 4N  
3 -# createtime: 2021/1/27  
4 -# email: nheweijun@sina.com  
5 -  
6 -from osgeo.ogr import *  
7 -import uuid  
8 -  
9 -import time  
10 -from app.models import *  
11 -import json  
12 -import re  
13 -from app.util.component.ApiTemplate import ApiTemplate  
14 -from app.util.component.PGUtil import PGUtil  
15 -  
16 -  
17 -class Api(ApiTemplate):  
18 - api_name = "检查meta"  
19 - def process(self):  
20 -  
21 - # 设置任务信息  
22 - self.para["task_guid"] = uuid.uuid1().__str__()  
23 - self.para["task_time"] = time.time()  
24 -  
25 - # 返回结果  
26 - res = {}  
27 -  
28 - try:  
29 -  
30 -  
31 - # 图层重名检查  
32 -  
33 - meta_list: list = json.loads(self.para.get("meta").__str__())  
34 - check_meta_only = int(self.para.get("check_meta_only", 0))  
35 -  
36 - res["data"] = {}  
37 -  
38 -  
39 - database = Database.query.filter_by(guid=self.para.get("database_guid")).one_or_none()  
40 - if not database:  
41 - raise Exception("数据库不存在!")  
42 - pg_ds: DataSource = PGUtil.open_pg_data_source(1, DES.decode(database.sqlalchemy_uri))  
43 -  
44 - res["result"] = True  
45 -  
46 - for meta in meta_list:  
47 - layers: dict = meta.get("layer")  
48 - for layer_name_origin in layers.keys():  
49 - layer_name = layers.get(layer_name_origin)  
50 - if pg_ds.GetLayerByName(layer_name) or InsertingLayerName.query.filter_by(  
51 - name=layer_name).one_or_none():  
52 - res["data"][layer_name_origin] = 0  
53 - res["result"] = False  
54 - # 判断特殊字符  
55 - elif re.search(r"\W", layer_name):  
56 - res["data"][layer_name_origin] = -1  
57 - res["result"] = False  
58 - else:  
59 - res["data"][layer_name_origin] = 1  
60 - if pg_ds:  
61 - try:  
62 - pg_ds.Destroy()  
63 - except:  
64 - print("关闭数据库失败!")  
65 -  
66 - except Exception as e:  
67 - raise e  
68 -  
69 - return res  
70 -  
71 - api_doc = {  
72 - "tags": ["IO接口"],  
73 - "parameters": [  
74 - {"name": "meta",  
75 - "in": "formData",  
76 - "type": "string",  
77 - "description": "数据meta"}  
78 - ],  
79 - "responses": {  
80 - 200: {  
81 - "schema": {  
82 - "properties": {  
83 - }  
84 - }  
85 - }  
86 - } 1 +# coding=utf-8
  2 +# author: 4N
  3 +# createtime: 2021/1/27
  4 +# email: nheweijun@sina.com
  5 +
  6 +from osgeo.ogr import *
  7 +import uuid
  8 +
  9 +import time
  10 +from app.models import *
  11 +import json
  12 +import re
  13 +from app.util.component.ApiTemplate import ApiTemplate
  14 +from app.util.component.PGUtil import PGUtil
  15 +
  16 +
  17 +class Api(ApiTemplate):
  18 + api_name = "检查meta"
  19 + def process(self):
  20 +
  21 + # 设置任务信息
  22 + self.para["task_guid"] = uuid.uuid1().__str__()
  23 + self.para["task_time"] = time.time()
  24 +
  25 + # 返回结果
  26 + res = {}
  27 +
  28 + try:
  29 +
  30 +
  31 + # 图层重名检查
  32 +
  33 + meta_list: list = json.loads(self.para.get("meta").__str__())
  34 + check_meta_only = int(self.para.get("check_meta_only", 0))
  35 +
  36 + res["data"] = {}
  37 +
  38 +
  39 + database = Database.query.filter_by(guid=self.para.get("database_guid")).one_or_none()
  40 + if not database:
  41 + raise Exception("数据库不存在!")
  42 + pg_ds: DataSource = PGUtil.open_pg_data_source(1, DES.decode(database.sqlalchemy_uri))
  43 +
  44 + res["result"] = True
  45 +
  46 + for meta in meta_list:
  47 + layers: dict = meta.get("layer")
  48 + for layer_name_origin in layers.keys():
  49 + layer_name = layers.get(layer_name_origin)
  50 + if pg_ds.GetLayerByName(layer_name) or InsertingLayerName.query.filter_by(
  51 + name=layer_name).one_or_none():
  52 + res["data"][layer_name_origin] = 0
  53 + res["result"] = False
  54 + # 判断特殊字符
  55 + elif re.search(r"\W", layer_name):
  56 + res["data"][layer_name_origin] = -1
  57 + res["result"] = False
  58 + else:
  59 + res["data"][layer_name_origin] = 1
  60 + if pg_ds:
  61 + try:
  62 + pg_ds.Destroy()
  63 + except:
  64 + print("关闭数据库失败!")
  65 +
  66 + except Exception as e:
  67 + raise e
  68 +
  69 + return res
  70 +
  71 + api_doc = {
  72 + "tags": ["IO接口"],
  73 + "parameters": [
  74 + {"name": "meta",
  75 + "in": "formData",
  76 + "type": "string",
  77 + "description": "数据meta"}
  78 + ],
  79 + "responses": {
  80 + 200: {
  81 + "schema": {
  82 + "properties": {
  83 + }
  84 + }
  85 + }
  86 + }
87 } 87 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2020/11/27  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from app.models import *  
8 -  
9 -import traceback  
10 -  
11 -from osgeo.ogr import DataSource,Layer,FeatureDefn,FieldDefn  
12 -from osgeo import gdal ,ogr  
13 -import os  
14 -import uuid  
15 -import configure  
16 -from app.util.component.ApiTemplate import ApiTemplate  
17 -from app.util.component.PGUtil import PGUtil  
18 -from app.util.component.ZipUtil import ZipUtil  
19 -class Api(ApiTemplate):  
20 -  
21 - api_name = "下载数据"  
22 - def process(self):  
23 - #获取参数  
24 -  
25 - #返回结果  
26 - res={}  
27 - #设置编码  
28 - encoding = self.para.get("encoding")  
29 - if encoding:  
30 - gdal.SetConfigOption("SHAPE_ENCODING",encoding)  
31 - else:  
32 - gdal.SetConfigOption("SHAPE_ENCODING", "GBK")  
33 -  
34 - ds:DataSource = None  
35 - try:  
36 - table_names = self.para.get("table_name").split(",")  
37 - database_guid = self.para.get("database_guid")  
38 - database = Database.query.filter_by(guid=database_guid).one_or_none()  
39 - if not database:  
40 - raise Exception("数据库不存在!")  
41 -  
42 - ds:DataSource = PGUtil.open_pg_data_source(0,DES.decode(database.sqlalchemy_uri))  
43 -  
44 - download_type = self.para.get("download_type")  
45 -  
46 - data = None  
47 - if download_type.__eq__("shp"):  
48 - data = self.download_shp(table_names,ds)  
49 - if download_type.__eq__("gdb"):  
50 - data = self.download_gdb(table_names, ds,database_guid)  
51 -  
52 - res["data"] = data  
53 - res["result"] = True  
54 - except Exception as e:  
55 - print(traceback.format_exc())  
56 - res["msg"]= e.__str__()  
57 - res["result"]=False  
58 - finally:  
59 - if ds:  
60 - ds.Destroy()  
61 - return res  
62 -  
63 -  
64 - def download_shp(self,table_names,ds):  
65 - data = []  
66 - for table_name in table_names:  
67 - url = self.download_one(ds, table_name)  
68 - data.append({"name": table_name, "download_url": url})  
69 - return data  
70 -  
71 - def download_one(self,ds,table_name):  
72 -  
73 - layer: Layer = ds.GetLayerByName(table_name)  
74 - driver = ogr.GetDriverByName("ESRI Shapefile")  
75 - uuid_ = uuid.uuid1().__str__()  
76 - parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  
77 - dirpath = os.path.join(parent, "file_tmp", uuid_)  
78 - os.makedirs(dirpath)  
79 - data_source: DataSource = driver.CreateDataSource(dirpath + "/{}.shp".format(table_name))  
80 - data_source.CopyLayer(layer, table_name)  
81 - data_source.Destroy()  
82 - ZipUtil.create_zip(os.path.join(parent, "file_tmp", table_name+"_"+uuid_) + ".zip", [dirpath])  
83 - return "http://" + configure.deploy_ip_host + "/API/IO/Download/{}".format(table_name+"_"+uuid_ + ".zip")  
84 -  
85 -  
86 - def download_gdb(self,table_names,ds,database_guid):  
87 - ogr.RegisterAll()  
88 - data = []  
89 - gdal.UseExceptions()  
90 - gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")  
91 -  
92 - # 创建一个gdb datasource  
93 - gdb_driver = ogr.GetDriverByName('FileGDB')  
94 - uuid_ = uuid.uuid1().__str__()  
95 - parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  
96 - gdb_path = os.path.join(parent, "file_tmp", uuid_+".gdb")  
97 - gdb_ds: DataSource = gdb_driver.CreateDataSource(gdb_path)  
98 -  
99 -  
100 - for table_name in table_names:  
101 -  
102 - layer: Layer = ds.GetLayerByName(table_name)  
103 - table = Table.query.filter_by(name=table_name, database_guid=database_guid).one_or_none()  
104 - feature_defn: FeatureDefn = layer.GetLayerDefn()  
105 -  
106 - for i in range(feature_defn.GetFieldCount()):  
107 - field_defn:FieldDefn = feature_defn.GetFieldDefn(i)  
108 - field_alias = Columns.query.filter_by(table_guid=table.guid,name=field_defn.GetName()).one_or_none().alias  
109 - field_defn.SetAlternativeName(field_alias)  
110 -  
111 - table_alias= table.alias  
112 -  
113 - # if is_chinese(table_name):  
114 - # if not table_alias:  
115 - # table_alias = table_name  
116 - # table_name = "table{}".format(table_name.__hash__())  
117 -  
118 - gdb_ds.CopyLayer(layer, table_name,["LAYER_ALIAS={}".format(table_alias)])  
119 -  
120 - gdb_ds.Destroy()  
121 - ZipUtil.create_zip(gdb_path + ".zip", [gdb_path])  
122 - data.append({"name": ",".join(table_names), "download_url": "http://" + configure.deploy_ip_host + "/API/IO/Download/{}".format(uuid_+".gdb" + ".zip")})  
123 -  
124 -  
125 - return data  
126 -  
127 -  
128 -  
129 - api_doc={  
130 - "tags":["IO接口"],  
131 - "description":"下载数据",  
132 - "parameters":[  
133 - {"name": "table_name",  
134 - "in": "formData",  
135 - "type":"string","description":"支持多图层下载,以逗号相隔","required":"true"},  
136 - {"name": "encoding",  
137 - "in": "formData",  
138 - "type": "string",  
139 - "enum":["GBK","UTF-8"]},  
140 - {"name": "download_type",  
141 - "in": "formData",  
142 - "type": "string",  
143 - "enum": ["shp", "gdb"],"required":"true"  
144 - },  
145 - {"name": "database_guid",  
146 - "in": "formData",  
147 - "type": "string","required":"true"  
148 - }  
149 - ],  
150 - "responses":{  
151 - 200:{  
152 - "schema":{  
153 - "properties":{  
154 - "content":{  
155 - "type": "string",  
156 - "description": "The name of the user"  
157 - }  
158 - }  
159 - }  
160 - }  
161 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2020/11/27
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from app.models import *
  8 +
  9 +import traceback
  10 +
  11 +from osgeo.ogr import DataSource,Layer,FeatureDefn,FieldDefn
  12 +from osgeo import gdal ,ogr
  13 +import os
  14 +import uuid
  15 +import configure
  16 +from app.util.component.ApiTemplate import ApiTemplate
  17 +from app.util.component.PGUtil import PGUtil
  18 +from app.util.component.ZipUtil import ZipUtil
  19 +class Api(ApiTemplate):
  20 +
  21 + api_name = "下载数据"
  22 + def process(self):
  23 + #获取参数
  24 +
  25 + #返回结果
  26 + res={}
  27 + #设置编码
  28 + encoding = self.para.get("encoding")
  29 + if encoding:
  30 + gdal.SetConfigOption("SHAPE_ENCODING",encoding)
  31 + else:
  32 + gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
  33 +
  34 + ds:DataSource = None
  35 + try:
  36 + table_names = self.para.get("table_name").split(",")
  37 + database_guid = self.para.get("database_guid")
  38 + database = Database.query.filter_by(guid=database_guid).one_or_none()
  39 + if not database:
  40 + raise Exception("数据库不存在!")
  41 +
  42 + ds:DataSource = PGUtil.open_pg_data_source(0,DES.decode(database.sqlalchemy_uri))
  43 +
  44 + download_type = self.para.get("download_type")
  45 +
  46 + data = None
  47 + if download_type.__eq__("shp"):
  48 + data = self.download_shp(table_names,ds)
  49 + if download_type.__eq__("gdb"):
  50 + data = self.download_gdb(table_names, ds,database_guid)
  51 +
  52 + res["data"] = data
  53 + res["result"] = True
  54 + except Exception as e:
  55 + print(traceback.format_exc())
  56 + res["msg"]= e.__str__()
  57 + res["result"]=False
  58 + finally:
  59 + if ds:
  60 + ds.Destroy()
  61 + return res
  62 +
  63 +
  64 + def download_shp(self,table_names,ds):
  65 + data = []
  66 + for table_name in table_names:
  67 + url = self.download_one(ds, table_name)
  68 + data.append({"name": table_name, "download_url": url})
  69 + return data
  70 +
  71 + def download_one(self,ds,table_name):
  72 +
  73 + layer: Layer = ds.GetLayerByName(table_name)
  74 + driver = ogr.GetDriverByName("ESRI Shapefile")
  75 + uuid_ = uuid.uuid1().__str__()
  76 + parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  77 + dirpath = os.path.join(parent, "file_tmp", uuid_)
  78 + os.makedirs(dirpath)
  79 + data_source: DataSource = driver.CreateDataSource(dirpath + "/{}.shp".format(table_name))
  80 + data_source.CopyLayer(layer, table_name)
  81 + data_source.Destroy()
  82 + ZipUtil.create_zip(os.path.join(parent, "file_tmp", table_name+"_"+uuid_) + ".zip", [dirpath])
  83 + return "http://" + configure.deploy_ip_host + "/API/IO/Download/{}".format(table_name+"_"+uuid_ + ".zip")
  84 +
  85 +
  86 + def download_gdb(self,table_names,ds,database_guid):
  87 + ogr.RegisterAll()
  88 + data = []
  89 + gdal.UseExceptions()
  90 + gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
  91 +
  92 + # 创建一个gdb datasource
  93 + gdb_driver = ogr.GetDriverByName('FileGDB')
  94 + uuid_ = uuid.uuid1().__str__()
  95 + parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  96 + gdb_path = os.path.join(parent, "file_tmp", uuid_+".gdb")
  97 + gdb_ds: DataSource = gdb_driver.CreateDataSource(gdb_path)
  98 +
  99 +
  100 + for table_name in table_names:
  101 +
  102 + layer: Layer = ds.GetLayerByName(table_name)
  103 + table = Table.query.filter_by(name=table_name, database_guid=database_guid).one_or_none()
  104 + feature_defn: FeatureDefn = layer.GetLayerDefn()
  105 +
  106 + for i in range(feature_defn.GetFieldCount()):
  107 + field_defn:FieldDefn = feature_defn.GetFieldDefn(i)
  108 + field_alias = Columns.query.filter_by(table_guid=table.guid,name=field_defn.GetName()).one_or_none().alias
  109 + field_defn.SetAlternativeName(field_alias)
  110 +
  111 + table_alias= table.alias
  112 +
  113 + # if is_chinese(table_name):
  114 + # if not table_alias:
  115 + # table_alias = table_name
  116 + # table_name = "table{}".format(table_name.__hash__())
  117 +
  118 + gdb_ds.CopyLayer(layer, table_name,["LAYER_ALIAS={}".format(table_alias)])
  119 +
  120 + gdb_ds.Destroy()
  121 + ZipUtil.create_zip(gdb_path + ".zip", [gdb_path])
  122 + data.append({"name": ",".join(table_names), "download_url": "http://" + configure.deploy_ip_host + "/API/IO/Download/{}".format(uuid_+".gdb" + ".zip")})
  123 +
  124 +
  125 + return data
  126 +
  127 +
  128 +
  129 + api_doc={
  130 + "tags":["IO接口"],
  131 + "description":"下载数据",
  132 + "parameters":[
  133 + {"name": "table_name",
  134 + "in": "formData",
  135 + "type":"string","description":"支持多图层下载,以逗号相隔","required":"true"},
  136 + {"name": "encoding",
  137 + "in": "formData",
  138 + "type": "string",
  139 + "enum":["GBK","UTF-8"]},
  140 + {"name": "download_type",
  141 + "in": "formData",
  142 + "type": "string",
  143 + "enum": ["shp", "gdb"],"required":"true"
  144 + },
  145 + {"name": "database_guid",
  146 + "in": "formData",
  147 + "type": "string","required":"true"
  148 + }
  149 + ],
  150 + "responses":{
  151 + 200:{
  152 + "schema":{
  153 + "properties":{
  154 + "content":{
  155 + "type": "string",
  156 + "description": "The name of the user"
  157 + }
  158 + }
  159 + }
  160 + }
  161 + }
162 } 162 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/1/27  
4 -#email: nheweijun@sina.com  
5 -  
6 -from osgeo.ogr import *  
7 -import uuid  
8 -  
9 -import time  
10 -from app.models import *  
11 -import json  
12 -import re  
13 -from app.util.component.ApiTemplate import ApiTemplate  
14 -from app.util.component.PGUtil import PGUtil  
15 -  
16 -  
17 -  
18 -class Api(ApiTemplate):  
19 -  
20 - api_name = "通过meta入库"  
21 -  
22 - def process(self):  
23 -  
24 - #设置任务信息  
25 - self.para["task_guid"] = uuid.uuid1().__str__()  
26 - self.para["task_time"] = time.time()  
27 -  
28 - #返回结果  
29 - res={}  
30 -  
31 - try:  
32 - #检测目录  
33 - if Catalog.query.filter_by(pguid=self.para.get("guid")).all():  
34 - raise Exception("目录非子目录,不可入库!")  
35 -  
36 - # 图层重名检查  
37 - meta_list:list = json.loads(self.para.get("meta").__str__())  
38 - check_meta_only = int(self.para.get("check_meta_only",0))  
39 -  
40 - res["data"] = {}  
41 - if check_meta_only:  
42 -  
43 - database = Database.query.filter_by(guid=self.para.get("database_guid")).one_or_none()  
44 - if not database:  
45 - raise Exception("数据库不存在!")  
46 - pg_ds: DataSource = PGUtil.open_pg_data_source(1, DES.decode(database.sqlalchemy_uri))  
47 -  
48 - res["result"] = True  
49 -  
50 - for meta in meta_list:  
51 - layers:dict = meta.get("layer")  
52 - for layer_name_origin in layers.keys():  
53 - layer_name = layers.get(layer_name_origin)  
54 - if pg_ds.GetLayerByName(layer_name) or InsertingLayerName.query.filter_by(name=layer_name).one_or_none():  
55 - res["data"][layer_name_origin]=0  
56 - res["result"] = False  
57 - # 判断特殊字符  
58 - elif re.search(r"\W",layer_name):  
59 - res["data"][layer_name_origin]=-1  
60 - res["result"] = False  
61 - else :  
62 - res["data"][layer_name_origin] = 1  
63 -  
64 - if pg_ds:  
65 - try:  
66 - pg_ds.Destroy()  
67 - except:  
68 - print("关闭数据库失败!")  
69 - return res  
70 -  
71 - # 录入数据后台进程,录入主函数为entry  
72 - # 初始化task  
73 - task = Task(guid=self.para.get("task_guid"),  
74 - name=self.para.get("task_name"),  
75 - create_time=datetime.datetime.now(),  
76 - state=0,  
77 - creator=self.para.get("creator"),  
78 - file_name=meta_list[0].get("filename"),  
79 - database_guid=self.para.get("database_guid"),  
80 - catalog_guid=self.para.get("catalog_guid"),  
81 - process="等待入库",  
82 - parameter=json.dumps(self.para))  
83 - db.session.add(task)  
84 - db.session.commit()  
85 -  
86 - res["result"] = True  
87 - res["msg"] = "数据录入提交成功!"  
88 - res["data"] = self.para["task_guid"]  
89 - except Exception as e:  
90 - raise e  
91 - return res  
92 -  
93 -  
94 - api_doc={  
95 - "tags":["IO接口"],  
96 - "parameters":[  
97 - {"name": "meta",  
98 - "in": "formData",  
99 - "type": "string",  
100 - "description": "数据meta"},  
101 - {"name": "encoding",  
102 - "in": "formData",  
103 - "type": "string",  
104 - "description": "原shp文件编码,非必要,优先使用cpg文件中编码,没有则默认GBK","enum":["UTF-8","GBK"]},  
105 - {"name": "overwrite",  
106 - "in": "formData",  
107 - "type": "string",  
108 - "description": "是否覆盖",  
109 - "enum":["yes","no"]},  
110 - {"name": "fid",  
111 - "in": "formData",  
112 - "type": "string",  
113 - "description": "fid列名"},  
114 - {"name": "geom_name",  
115 - "in": "formData",  
116 - "type": "string",  
117 - "description": "空间属性列名"},  
118 - {"name": "task_name",  
119 - "in": "formData",  
120 - "type": "string",  
121 - "description": "任务名",  
122 - "required":"true"},  
123 - {"name": "creator",  
124 - "in": "formData",  
125 - "type": "string",  
126 - "description": "创建人"},  
127 - {"name": "database_guid",  
128 - "in": "formData",  
129 - "type": "string",  
130 - "description": "数据库guid",  
131 - "required": "true"},  
132 - {"name": "catalog_guid",  
133 - "in": "formData",  
134 - "type": "string",  
135 - "description": "目录guid"},  
136 - {"name": "check_meta_only",  
137 - "in": "formData",  
138 - "type": "int",  
139 - "description": "是否只检查meta","enum":[0,1]}  
140 -  
141 - ],  
142 - "responses":{  
143 - 200:{  
144 - "schema":{  
145 - "properties":{  
146 - }  
147 - }  
148 - }  
149 - } 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/1/27
  4 +#email: nheweijun@sina.com
  5 +
  6 +from osgeo.ogr import *
  7 +import uuid
  8 +
  9 +import time
  10 +from app.models import *
  11 +import json
  12 +import re
  13 +from app.util.component.ApiTemplate import ApiTemplate
  14 +from app.util.component.PGUtil import PGUtil
  15 +
  16 +
  17 +
  18 +class Api(ApiTemplate):
  19 +
  20 + api_name = "通过meta入库"
  21 +
  22 + def process(self):
  23 +
  24 + #设置任务信息
  25 + self.para["task_guid"] = uuid.uuid1().__str__()
  26 + self.para["task_time"] = time.time()
  27 +
  28 + #返回结果
  29 + res={}
  30 +
  31 + try:
  32 + #检测目录
  33 + if Catalog.query.filter_by(pguid=self.para.get("guid")).all():
  34 + raise Exception("目录非子目录,不可入库!")
  35 +
  36 + # 图层重名检查
  37 + meta_list:list = json.loads(self.para.get("meta").__str__())
  38 + check_meta_only = int(self.para.get("check_meta_only",0))
  39 +
  40 + res["data"] = {}
  41 + if check_meta_only:
  42 +
  43 + database = Database.query.filter_by(guid=self.para.get("database_guid")).one_or_none()
  44 + if not database:
  45 + raise Exception("数据库不存在!")
  46 + pg_ds: DataSource = PGUtil.open_pg_data_source(1, DES.decode(database.sqlalchemy_uri))
  47 +
  48 + res["result"] = True
  49 +
  50 + for meta in meta_list:
  51 + layers:dict = meta.get("layer")
  52 + for layer_name_origin in layers.keys():
  53 + layer_name = layers.get(layer_name_origin)
  54 + if pg_ds.GetLayerByName(layer_name) or InsertingLayerName.query.filter_by(name=layer_name).one_or_none():
  55 + res["data"][layer_name_origin]=0
  56 + res["result"] = False
  57 + # 判断特殊字符
  58 + elif re.search(r"\W",layer_name):
  59 + res["data"][layer_name_origin]=-1
  60 + res["result"] = False
  61 + else :
  62 + res["data"][layer_name_origin] = 1
  63 +
  64 + if pg_ds:
  65 + try:
  66 + pg_ds.Destroy()
  67 + except:
  68 + print("关闭数据库失败!")
  69 + return res
  70 +
  71 + # 录入数据后台进程,录入主函数为entry
  72 + # 初始化task
  73 + task = Task(guid=self.para.get("task_guid"),
  74 + name=self.para.get("task_name"),
  75 + create_time=datetime.datetime.now(),
  76 + state=0,
  77 + task_type=1,
  78 + creator=self.para.get("creator"),
  79 + file_name=meta_list[0].get("filename"),
  80 + database_guid=self.para.get("database_guid"),
  81 + catalog_guid=self.para.get("catalog_guid"),
  82 + process="等待入库",
  83 + parameter=json.dumps(self.para))
  84 + db.session.add(task)
  85 + db.session.commit()
  86 +
  87 + res["result"] = True
  88 + res["msg"] = "数据录入提交成功!"
  89 + res["data"] = self.para["task_guid"]
  90 + except Exception as e:
  91 + raise e
  92 + return res
  93 +
  94 +
  95 + api_doc={
  96 + "tags":["IO接口"],
  97 + "parameters":[
  98 + {"name": "meta",
  99 + "in": "formData",
  100 + "type": "string",
  101 + "description": "数据meta"},
  102 + {"name": "encoding",
  103 + "in": "formData",
  104 + "type": "string",
  105 + "description": "原shp文件编码,非必要,优先使用cpg文件中编码,没有则默认GBK","enum":["UTF-8","GBK"]},
  106 + {"name": "overwrite",
  107 + "in": "formData",
  108 + "type": "string",
  109 + "description": "是否覆盖",
  110 + "enum":["yes","no"]},
  111 + {"name": "fid",
  112 + "in": "formData",
  113 + "type": "string",
  114 + "description": "fid列名"},
  115 + {"name": "geom_name",
  116 + "in": "formData",
  117 + "type": "string",
  118 + "description": "空间属性列名"},
  119 + {"name": "task_name",
  120 + "in": "formData",
  121 + "type": "string",
  122 + "description": "任务名",
  123 + "required":"true"},
  124 + {"name": "creator",
  125 + "in": "formData",
  126 + "type": "string",
  127 + "description": "创建人"},
  128 + {"name": "database_guid",
  129 + "in": "formData",
  130 + "type": "string",
  131 + "description": "数据库guid",
  132 + "required": "true"},
  133 + {"name": "catalog_guid",
  134 + "in": "formData",
  135 + "type": "string",
  136 + "description": "目录guid"},
  137 + {"name": "check_meta_only",
  138 + "in": "formData",
  139 + "type": "int",
  140 + "description": "是否只检查meta","enum":[0,1]}
  141 +
  142 + ],
  143 + "responses":{
  144 + 200:{
  145 + "schema":{
  146 + "properties":{
  147 + }
  148 + }
  149 + }
  150 + }
150 } 151 }
1 -# coding=utf-8  
2 -# author: 4N  
3 -# createtime: 2020/9/4  
4 -# email: nheweijun@sina.com  
5 -  
6 -import traceback  
7 -from osgeo.ogr import *  
8 -from osgeo import ogr  
9 -  
10 -from flask import request  
11 -import os  
12 -import uuid  
13 -  
14 -import json  
15 -from app.util.component.ApiTemplate import ApiTemplate  
16 -from app.util.component.ZipUtil import ZipUtil  
17 -from app.util.component.FileProcess import FileProcess  
18 -import datetime  
19 -import time  
20 -class Api(ApiTemplate):  
21 - api_name = "本地数据list"  
22 - def process(self):  
23 - res = {}  
24 -  
25 - try:  
26 - project_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))  
27 - base_path = os.path.join(project_path,"tmp")  
28 - if self.para.get("data_path"):  
29 - base_path = os.path.normpath(self.para.get("data_path"))  
30 - data_list:list = []  
31 - for f in os.listdir(base_path):  
32 -  
33 - file_path = os.path.normpath(os.path.join(base_path, f))  
34 - file_size = FileProcess.get_file_size(file_path)  
35 -  
36 - fctime = datetime.datetime.fromtimestamp(os.path.getctime(file_path)).strftime('%Y-%m-%d %H:%M:%S')  
37 -  
38 - file_info ={"name":f,"path":file_path,"size":file_size,"create_time":fctime}  
39 -  
40 - if file_path.endswith("shp"):  
41 - file_info["type"]="shp"  
42 - data_list.append(file_info)  
43 - elif file_path.endswith("gdb"):  
44 - file_info["type"]="gdb"  
45 - data_list.append(file_info)  
46 - elif file_path.endswith("zip"):  
47 - file_info["type"]="zip"  
48 - data_list.append(file_info)  
49 - elif os.path.isdir(file_path):  
50 - bn = os.path.basename(file_path)  
51 - if not len(bn.split("-"))==5:  
52 - file_info["type"] = "dir"  
53 - data_list.append(file_info)  
54 -  
55 - data_list_sorted = sorted(data_list, key=lambda x: x["name"])  
56 - res["data"]=data_list_sorted  
57 - res["result"]=True  
58 - except Exception as e:  
59 - raise e  
60 - return res  
61 -  
62 -  
63 -  
64 - api_doc={  
65 - "tags":["IO接口"],  
66 - "parameters":[  
67 - {"name": "data_path",  
68 - "in": "formData",  
69 - "type": "string",  
70 - "description": "数据文件路径"}  
71 - ],  
72 - "responses":{  
73 - 200:{  
74 - "schema":{  
75 - "properties":{  
76 - }  
77 - }  
78 - }  
79 - } 1 +# coding=utf-8
  2 +# author: 4N
  3 +# createtime: 2020/9/4
  4 +# email: nheweijun@sina.com
  5 +
  6 +import traceback
  7 +from osgeo.ogr import *
  8 +from osgeo import ogr
  9 +
  10 +from flask import request
  11 +import os
  12 +import uuid
  13 +
  14 +import json
  15 +from app.util.component.ApiTemplate import ApiTemplate
  16 +from app.util.component.ZipUtil import ZipUtil
  17 +from app.util.component.FileProcess import FileProcess
  18 +import datetime
  19 +import time
  20 +class Api(ApiTemplate):
  21 + api_name = "本地数据list"
  22 + def process(self):
  23 + res = {}
  24 +
  25 + try:
  26 + project_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
  27 + base_path = os.path.join(project_path,"tmp")
  28 + if self.para.get("data_path"):
  29 + base_path = os.path.normpath(self.para.get("data_path"))
  30 + data_list:list = []
  31 + for f in os.listdir(base_path):
  32 +
  33 + file_path = os.path.normpath(os.path.join(base_path, f))
  34 + file_size = FileProcess.get_file_size(file_path)
  35 +
  36 + fctime = datetime.datetime.fromtimestamp(os.path.getctime(file_path)).strftime('%Y-%m-%d %H:%M:%S')
  37 +
  38 + file_info ={"name":f,"path":file_path,"size":file_size,"create_time":fctime}
  39 +
  40 + if file_path.endswith("shp"):
  41 + file_info["type"]="shp"
  42 + data_list.append(file_info)
  43 + elif file_path.endswith("gdb"):
  44 + file_info["type"]="gdb"
  45 + data_list.append(file_info)
  46 + elif file_path.endswith("zip"):
  47 + file_info["type"]="zip"
  48 + data_list.append(file_info)
  49 + elif os.path.isdir(file_path):
  50 + bn = os.path.basename(file_path)
  51 + if not len(bn.split("-"))==5:
  52 + file_info["type"] = "dir"
  53 + data_list.append(file_info)
  54 +
  55 + data_list_sorted = sorted(data_list, key=lambda x: x["name"])
  56 + res["data"]=data_list_sorted
  57 + res["result"]=True
  58 + except Exception as e:
  59 + raise e
  60 + return res
  61 +
  62 +
  63 +
  64 + api_doc={
  65 + "tags":["IO接口"],
  66 + "parameters":[
  67 + {"name": "data_path",
  68 + "in": "formData",
  69 + "type": "string",
  70 + "description": "数据文件路径"}
  71 + ],
  72 + "responses":{
  73 + 200:{
  74 + "schema":{
  75 + "properties":{
  76 + }
  77 + }
  78 + }
  79 + }
80 } 80 }
1 -# coding=utf-8  
2 -# author: 4N  
3 -# createtime: 2020/9/4  
4 -# email: nheweijun@sina.com  
5 -  
6 -import traceback  
7 -from osgeo.ogr import *  
8 -from osgeo import ogr  
9 -  
10 -from flask import request  
11 -import os  
12 -import uuid  
13 -  
14 -import json  
15 -from app.util.component.ApiTemplate import ApiTemplate  
16 -from app.util.component.ZipUtil import ZipUtil  
17 -from app.util.component.FileProcess import FileProcess  
18 -  
19 -  
20 -class Api(ApiTemplate):  
21 - api_name = "获取meta"  
22 - def process(self):  
23 - res = {}  
24 -  
25 - try:  
26 -  
27 - spatial_files=[]  
28 - if self.para.get("data_path"):  
29 - filename = os.path.basename(self.para.get("data_path"))  
30 - #处理  
31 -  
32 - if self.para.get("data_path").endswith("zip"):  
33 -  
34 - store_path = ZipUtil.unzip(self.para.get("data_path"),True)  
35 - spatial_files = FileProcess.get_spatial_file(store_path)  
36 -  
37 - elif self.para.get("data_path").endswith("shp"):  
38 - data_path=self.para.get("data_path")  
39 - encoding_cpg_path = data_path.split(".shp")[0]+".cpg"  
40 - with open(encoding_cpg_path) as fd:  
41 - encoding_cpg = fd.readline().strip()  
42 - if not os.path.exists(encoding_cpg_path):  
43 - encoding_cpg=None  
44 - spatial_files.append((data_path, encoding_cpg))  
45 - elif self.para.get("data_path").endswith("gdb"):  
46 - data_path=self.para.get("data_path")  
47 - encoding_cpg=None  
48 - spatial_files.append((data_path, encoding_cpg))  
49 - else:  
50 - raise Exception("文件不符合规格!")  
51 -  
52 - else:  
53 - # 保存文件  
54 - parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))  
55 - dir_path, store_file = FileProcess.save(parent)  
56 - store_path = ZipUtil.unzip(store_file)  
57 -  
58 - spatial_files = FileProcess.get_spatial_file(store_path)  
59 -  
60 - file = request.files['file']  
61 - filename = file.filename.split('"')[0]  
62 -  
63 - res["data"] =[]  
64 -  
65 - for data_path,code in spatial_files:  
66 - one_data = self.get_meta(data_path)  
67 - one_data["encoding"]=code  
68 - one_data["filename"] = filename  
69 - res["data"].append(one_data)  
70 - res["result"] = True  
71 -  
72 - except Exception as e:  
73 - raise e  
74 - return json.dumps(res,ensure_ascii=False)  
75 -  
76 -  
77 - def get_meta(self,data_path):  
78 - ds: DataSource = None  
79 - info = {}  
80 - layer_name = {}  
81 - info["data_path"] = os.path.normpath(data_path)  
82 - info["layer"] =layer_name  
83 - try:  
84 - # 分为shp和gdb 2种  
85 - if data_path.endswith("shp"):  
86 - info["type"]="shp"  
87 - driver: Driver = ogr.GetDriverByName("ESRI Shapefile")  
88 - ds: DataSource = driver.Open(data_path, 1)  
89 - if not ds:  
90 - raise Exception("打开数据失败!")  
91 - layer: Layer = ds.GetLayer(0)  
92 - layer_name[layer.GetName().lower()] = layer.GetName().lower()  
93 -  
94 - if data_path.endswith("gdb"):  
95 - info["type"] = "gdb"  
96 - driver: Driver = ogr.GetDriverByName("OpenFileGDB")  
97 - ds: DataSource = driver.Open(data_path, 0)  
98 - if not ds:  
99 - raise Exception("打开数据失败!")  
100 - for i in range(ds.GetLayerCount()):  
101 - layer: Layer = ds.GetLayer(i)  
102 - layer_name[layer.GetName().lower()] = layer.GetName().lower()  
103 - except Exception as e :  
104 - print(traceback.format_exc())  
105 - info={}  
106 - finally:  
107 - if ds:  
108 - ds.Destroy()  
109 - return info  
110 -  
111 -  
112 - api_doc={  
113 - "tags":["IO接口"],  
114 - "parameters":[  
115 - {"name": "file",  
116 - "in": "formData",  
117 - "type":"file",  
118 - "description":"数据文件zip压缩包"},  
119 - {"name": "data_path",  
120 - "in": "formData",  
121 - "type": "string",  
122 - "description": "数据文件路径"}  
123 - ],  
124 - "responses":{  
125 - 200:{  
126 - "schema":{  
127 - "properties":{  
128 - }  
129 - }  
130 - }  
131 - } 1 +# coding=utf-8
  2 +# author: 4N
  3 +# createtime: 2020/9/4
  4 +# email: nheweijun@sina.com
  5 +
  6 +import traceback
  7 +from osgeo.ogr import *
  8 +from osgeo import ogr
  9 +
  10 +from flask import request
  11 +import os
  12 +import uuid
  13 +
  14 +import json
  15 +from app.util.component.ApiTemplate import ApiTemplate
  16 +from app.util.component.ZipUtil import ZipUtil
  17 +from app.util.component.FileProcess import FileProcess
  18 +
  19 +
  20 +class Api(ApiTemplate):
  21 + api_name = "获取meta"
  22 + def process(self):
  23 + res = {}
  24 +
  25 + try:
  26 +
  27 + spatial_files=[]
  28 + if self.para.get("data_path"):
  29 + filename = os.path.basename(self.para.get("data_path"))
  30 + #处理
  31 +
  32 + if self.para.get("data_path").endswith("zip"):
  33 +
  34 + store_path = ZipUtil.unzip(self.para.get("data_path"),True)
  35 + spatial_files = FileProcess.get_spatial_file(store_path)
  36 +
  37 + elif self.para.get("data_path").endswith("shp"):
  38 + data_path=self.para.get("data_path")
  39 + encoding_cpg_path = data_path.split(".shp")[0]+".cpg"
  40 + with open(encoding_cpg_path) as fd:
  41 + encoding_cpg = fd.readline().strip()
  42 + if not os.path.exists(encoding_cpg_path):
  43 + encoding_cpg=None
  44 + spatial_files.append((data_path, encoding_cpg))
  45 + elif self.para.get("data_path").endswith("gdb"):
  46 + data_path=self.para.get("data_path")
  47 + encoding_cpg=None
  48 + spatial_files.append((data_path, encoding_cpg))
  49 + else:
  50 + raise Exception("文件不符合规格!")
  51 +
  52 + else:
  53 + # 保存文件
  54 + parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  55 + dir_path, store_file = FileProcess.save(parent)
  56 + store_path = ZipUtil.unzip(store_file)
  57 +
  58 + spatial_files = FileProcess.get_spatial_file(store_path)
  59 +
  60 + file = request.files['file']
  61 + filename = file.filename.split('"')[0]
  62 +
  63 + res["data"] =[]
  64 +
  65 + for data_path,code in spatial_files:
  66 + one_data = self.get_meta(data_path)
  67 + one_data["encoding"]=code
  68 + one_data["filename"] = filename
  69 + res["data"].append(one_data)
  70 + res["result"] = True
  71 +
  72 + except Exception as e:
  73 + raise e
  74 + return json.dumps(res,ensure_ascii=False)
  75 +
  76 +
  77 + def get_meta(self,data_path):
  78 + ds: DataSource = None
  79 + info = {}
  80 + layer_name = {}
  81 + info["data_path"] = os.path.normpath(data_path)
  82 + info["layer"] =layer_name
  83 + try:
  84 + # 分为shp和gdb 2种
  85 + if data_path.endswith("shp"):
  86 + info["type"]="shp"
  87 + driver: Driver = ogr.GetDriverByName("ESRI Shapefile")
  88 + ds: DataSource = driver.Open(data_path, 1)
  89 + if not ds:
  90 + raise Exception("打开数据失败!")
  91 + layer: Layer = ds.GetLayer(0)
  92 + layer_name[layer.GetName().lower()] = layer.GetName().lower()
  93 +
  94 + if data_path.endswith("gdb"):
  95 + info["type"] = "gdb"
  96 + driver: Driver = ogr.GetDriverByName("OpenFileGDB")
  97 + ds: DataSource = driver.Open(data_path, 0)
  98 + if not ds:
  99 + raise Exception("打开数据失败!")
  100 + for i in range(ds.GetLayerCount()):
  101 + layer: Layer = ds.GetLayer(i)
  102 + layer_name[layer.GetName().lower()] = layer.GetName().lower()
  103 + except Exception as e :
  104 + print(traceback.format_exc())
  105 + info={}
  106 + finally:
  107 + if ds:
  108 + ds.Destroy()
  109 + return info
  110 +
  111 +
  112 + api_doc={
  113 + "tags":["IO接口"],
  114 + "parameters":[
  115 + {"name": "file",
  116 + "in": "formData",
  117 + "type":"file",
  118 + "description":"数据文件zip压缩包"},
  119 + {"name": "data_path",
  120 + "in": "formData",
  121 + "type": "string",
  122 + "description": "数据文件路径"}
  123 + ],
  124 + "responses":{
  125 + 200:{
  126 + "schema":{
  127 + "properties":{
  128 + }
  129 + }
  130 + }
  131 + }
132 } 132 }
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2020/11/30  
4 -#email: nheweijun@sina.com  
5 -from app.util import *  
6 -import configure  
7 -from osgeo import ogr  
8 -  
9 -from configure import SQLALCHEMY_DATABASE_URI  
10 -from sqlalchemy import create_engine  
11 -from sqlalchemy.orm import sessionmaker, session  
12 -  
13 -  
14 -  
15 -  
16 -  
17 -  
18 -  
19 -  
20 - 1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2020/11/30
  4 +#email: nheweijun@sina.com
  5 +from app.util import *
  6 +import configure
  7 +from osgeo import ogr
  8 +
  9 +from configure import SQLALCHEMY_DATABASE_URI
  10 +from sqlalchemy import create_engine
  11 +from sqlalchemy.orm import sessionmaker, session
  12 +
  13 +
  14 +
  15 +
  16 +
  17 +
  18 +
  19 +
  20 +
1 -# coding=utf-8  
2 -#author: 4N  
3 -#createtime: 2021/3/1  
4 -#email: nheweijun@sina.com  
5 -  
6 -  
7 -from flasgger import swag_from  
8 -from flask import Blueprint  
9 -from app.util import BlueprintApi  
10 -  
11 -from . import field_edit  
12 -  
13 -from . import table_list  
14 -from . import field_list  
15 -from . import table_edit  
16 -from . import table_info  
17 -from . import table_refresh  
18 -from . import table_delete  
19 -from . import table_view  
20 -class DataManager(BlueprintApi):  
21 -  
22 - bp = Blueprint("DataManager", __name__, url_prefix="/API/Manager")  
23 -  
24 - @staticmethod  
25 - @bp.route('/FieldEdit', methods=['POST'])  
26 - @swag_from(field_edit.Api.api_doc)  
27 - def field_edit():  
28 - """  
29 - 修改属性别名  
30 - """  
31 - return field_edit.Api().result  
32 -  
33 - @staticmethod  
34 - @bp.route('/FieldList', methods=['POST'])  
35 - @swag_from(field_list.Api.api_doc)  
36 - def field_list():  
37 - """  
38 - 属性列表  
39 - """  
40 - return field_list.Api().result  
41 -  
42 - @staticmethod  
43 - @bp.route('/TableList', methods=['POST'])  
44 - @swag_from(table_list.Api.api_doc)  
45 - def table_list():  
46 - """  
47 - 数据列表  
48 - """  
49 - return table_list.Api().result  
50 -  
51 -  
52 - @staticmethod  
53 - @bp.route('/TableEdit', methods=['POST'])  
54 - @swag_from(table_edit.Api.api_doc)  
55 - def table_edit():  
56 - """  
57 - 修改数据  
58 - """  
59 - return table_edit.Api().result  
60 -  
61 -  
62 - @staticmethod  
63 - @bp.route('/TableDelete', methods=['POST'])  
64 - @swag_from(table_delete.Api.api_doc)  
65 - def table_delete():  
66 - """  
67 - 删除数据  
68 - """  
69 - return table_delete.Api().result  
70 -  
71 -  
72 - @staticmethod  
73 - @bp.route('/TableInfo', methods=['POST'])  
74 - @swag_from(table_info.Api.api_doc)  
75 - def table_info():  
76 - """  
77 - 数据信息  
78 - """  
79 - return table_info.Api().result  
80 -  
81 -  
82 - @staticmethod  
83 - @bp.route('/TableRefresh', methods=['POST'])  
84 - @swag_from(table_refresh.Api.api_doc)  
85 - def table_refresh():  
86 - """  
87 - 刷新数据  
88 - """  
89 - return table_refresh.Api().result  
90 -  
91 - @staticmethod  
92 - @bp.route('/TableView', methods=['POST'])  
93 - @swag_from(table_view.Api.api_doc)  
94 - def table_view():  
95 - """  
96 - 数据浏览  
97 - """  
98 - return table_view.Api().result  
  1 +# coding=utf-8
  2 +#author: 4N
  3 +#createtime: 2021/3/1
  4 +#email: nheweijun@sina.com
  5 +
  6 +
  7 +from flasgger import swag_from
  8 +from flask import Blueprint
  9 +from app.util import BlueprintApi
  10 +
  11 +from . import field_edit
  12 +
  13 +from . import table_list
  14 +from . import field_list
  15 +from . import table_edit
  16 +from . import table_info
  17 +from . import table_refresh
  18 +from . import table_delete
  19 +from . import table_view
  20 +from . import table_vacuate
  21 +class DataManager(BlueprintApi):
  22 +
  23 + bp = Blueprint("DataManager", __name__, url_prefix="/API/Manager")
  24 +
  25 + @staticmethod
  26 + @bp.route('/FieldEdit', methods=['POST'])
  27 + @swag_from(field_edit.Api.api_doc)
  28 + def field_edit():
  29 + """
  30 + 修改属性别名
  31 + """
  32 + return field_edit.Api().result
  33 +
  34 + @staticmethod
  35 + @bp.route('/FieldList', methods=['POST'])
  36 + @swag_from(field_list.Api.api_doc)
  37 + def field_list():
  38 + """
  39 + 属性列表
  40 + """
  41 + return field_list.Api().result
  42 +
  43 + @staticmethod
  44 + @bp.route('/TableList', methods=['POST'])
  45 + @swag_from(table_list.Api.api_doc)
  46 + def table_list():
  47 + """
  48 + 数据列表
  49 + """
  50 + return table_list.Api().result
  51 +
  52 +
  53 + @staticmethod
  54 + @bp.route('/TableEdit', methods=['POST'])
  55 + @swag_from(table_edit.Api.api_doc)
  56 + def table_edit():
  57 + """
  58 + 修改数据
  59 + """
  60 + return table_edit.Api().result
  61 +
  62 +
  63 + @staticmethod
  64 + @bp.route('/TableDelete', methods=['POST'])
  65 + @swag_from(table_delete.Api.api_doc)
  66 + def table_delete():
  67 + """
  68 + 删除数据
  69 + """
  70 + return table_delete.Api().result
  71 +
  72 +
  73 + @staticmethod
  74 + @bp.route('/TableInfo', methods=['POST'])
  75 + @swag_from(table_info.Api.api_doc)
  76 + def table_info():
  77 + """
  78 + 数据信息
  79 + """
  80 + return table_info.Api().result
  81 +
  82 +
  83 + @staticmethod
  84 + @bp.route('/TableRefresh', methods=['POST'])
  85 + @swag_from(table_refresh.Api.api_doc)
  86 + def table_refresh():
  87 + """
  88 + 刷新数据
  89 + """
  90 + return table_refresh.Api().result
  91 +
  92 + @staticmethod
  93 + @bp.route('/TableView', methods=['POST'])
  94 + @swag_from(table_view.Api.api_doc)
  95 + def table_view():
  96 + """
  97 + 数据浏览
  98 + """
  99 + return table_view.Api().result
  100 +
  101 +
  102 + @staticmethod
  103 + @bp.route('/TableVacuate', methods=['POST'])
  104 + @swag_from(table_vacuate.Api.api_doc)
  105 + def table_vacuate():
  106 + """
  107 + 数据抽稀
  108 + """
  109 + return table_vacuate.Api().result
注册登录 后发表评论