data_download_task.py
10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# coding=utf-8
#author: 4N
#createtime: 2020/11/27
#email: nheweijun@sina.com
from ..models import *
import traceback
from .util.SchemaAdapter import SchemaAdapter
from osgeo.ogr import DataSource,Layer,FeatureDefn,FieldDefn,Feature
from osgeo import gdal,ogr
import os
import uuid
import configure
from app.util.component.ApiTemplate import ApiTemplate
from app.util.component.PGUtil import PGUtil
from app.util.component.ZipUtil import ZipUtil
from app.util.component.StructurePrint import StructurePrint
import multiprocessing
import datetime
from app.util.component.TaskController import TaskController
from app.util.component.TaskWriter import TaskWriter
class Api(ApiTemplate):
api_name = "数据下载"
def process(self):
res = {}
#获取参数
try:
task_guid = uuid.uuid1().__str__()
task = Task(guid=task_guid,
name="下载 | {}".format(self.para.get("table_name")),
create_time=datetime.datetime.now(),
state=0,
task_type=4,
creator=self.para.get("creator"),
file_name=None,
process="数据下载中",
database_guid=self.para.get("database_guid"),
# task_pid=download_process.pid
)
db.session.add(task)
db.session.commit()
download_process = multiprocessing.Process(target=self.download, args=(task_guid,self.para))
download_process.start()
task.task_pid = download_process.pid
db.session.commit()
res["data"] = "下载任务已提交!"
# 提示信息
res["msg"] = "下载格式为shp时,属性名长度超过10个字符将截取为10个字符,binary类型的属性将改成integer类型且值为0。"
res["msg"] = ""
res["result"] = True
except Exception as e:
raise e
return res
def download(self,task_guid,para):
ds: DataSource = None
task_writer = None
# 设置编码
# encoding = para.get("encoding")
# if encoding:
# gdal.SetConfigOption("SHAPE_ENCODING", encoding)
# else:
# gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
try:
#任务控制,等待执行
TaskController.wait(task_guid)
task_writer = TaskWriter(task_guid)
task_writer.update_task({"state":2,"update_time":datetime.datetime.now(),"process" : "下载中"})
task_writer.update_process("开始下载...")
table_names = para.get("table_name").split(",")
database_guid = para.get("database_guid")
database = task_writer.session.query(Database).filter_by(guid=database_guid).one_or_none()
if not database:
raise Exception("数据库不存在!")
ds: DataSource = PGUtil.open_pg_data_source(0, DES.decode(database.sqlalchemy_uri))
download_type = para.get("download_type")
data = None
if download_type.__eq__("shp"):
data = self.download_shp(table_names, ds)
if download_type.__eq__("gdb"):
data = self.download_gdb(task_writer.session,table_names, ds, database_guid)
task_writer.update_task({"state":1,"update_time":datetime.datetime.now(),"process" : "下载完成","parameter":data[0]["download_url"]})
task_writer.update_process("下载完成!")
except Exception as e:
try:
task_writer.update_task({"state": -1,"update_time":datetime.datetime.now(),"process": "下载失败"})
task_writer.update_process( e.__str__())
task_writer.update_process("任务中止!")
except Exception as ee:
StructurePrint().print(ee.__str__())
raise e
finally:
try:
if ds:
ds.Destroy()
task_writer.close()
except Exception as e:
StructurePrint().print(e.__str__())
def download_shp(self,table_names,ds):
data = []
for table_name in table_names:
url = self.download_one(ds, table_name)
data.append({"name": table_name, "download_url": url})
return data
def download_one(self,ds,table_name):
layer: Layer = ds.GetLayerByName(table_name)
driver = ogr.GetDriverByName("ESRI Shapefile")
uuid_ = uuid.uuid1().__str__()
parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
dirpath = os.path.join(parent, "file_tmp", uuid_)
os.makedirs(dirpath)
data_source: DataSource = driver.CreateDataSource(dirpath + "/{}.shp".format(table_name))
fid = layer.GetFIDColumn()
pg_layer: Layer = data_source.CreateLayer(table_name, layer.GetSpatialRef(), layer.GetGeomType(),["ENCODING=GBK"])
schema = [sche for sche in layer.schema if not sche.name.__eq__(fid)]
# 忽略binary字段
SchemaAdapter.neglect_binary(schema)
pg_layer.CreateFields(schema)
layer.ResetReading()
count = 0
for feature in layer:
pg_layer.CreateFeature(feature)
count += 1
if count % 10000 == 0:
StructurePrint().print("{}图层已下载{}个对象".format(table_name, count))
data_source.Destroy()
#增加cpg文件
with open(dirpath + "/{}.cpg".format(table_name),"w") as f:
f.write("GBK")
zip_uuid_ = uuid.uuid1().__str__()
zippath = os.path.join(parent, "file_tmp", zip_uuid_)
os.makedirs(zippath)
# ZipUtil.create_zip(os.path.join(parent, "file_tmp", table_name+"_"+uuid_) + ".zip", [dirpath])
#return "http://" + configure.deploy_ip_host + "/API/IO/Download/{}".format(table_name + "_" + uuid_ + ".zip")
files = []
for f in os.listdir(dirpath):
files.append(os.path.join(dirpath, f))
ZipUtil.create_zip(os.path.join(zippath, table_name) + ".zip", files)
return "http://" + configure.deploy_ip_host + "/API/IO/Download/{}/{}".format(zip_uuid_,table_name+ ".zip")
def download_gdb(self,sys_session,table_names,ds,database_guid):
ogr.RegisterAll()
data = []
gdal.UseExceptions()
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
# 创建一个gdb datasource
gdb_driver = ogr.GetDriverByName('FileGDB')
if not gdb_driver:
raise Exception("目前不支持GDB下载,驱动不存在!")
uuid_ = uuid.uuid1().__str__()
parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
dirpath = os.path.join(parent, "file_tmp", uuid_)
os.makedirs(dirpath)
gdb_path = os.path.join(parent, "file_tmp", uuid_, table_names[0]+".gdb")
gdb_ds: DataSource = gdb_driver.CreateDataSource(gdb_path)
for table_name in table_names:
layer: Layer = ds.GetLayerByName(table_name)
table = sys_session.query(Table).filter_by(name=table_name, database_guid=database_guid).one_or_none()
feature_defn: FeatureDefn = layer.GetLayerDefn()
for i in range(feature_defn.GetFieldCount()):
field_defn:FieldDefn = feature_defn.GetFieldDefn(i)
field_alias = sys_session.query(Columns).filter_by(table_guid=table.guid,name=field_defn.GetName()).one_or_none().alias
field_defn.SetAlternativeName(field_alias)
table_alias= table.alias if table.alias is not None else table_name
fid = layer.GetFIDColumn()
pg_layer: Layer = gdb_ds.CreateLayer(table_name, layer.GetSpatialRef(), layer.GetGeomType(),["LAYER_ALIAS={}".format(table_alias)])
schema = [sche for sche in layer.schema if not sche.name.__eq__(fid)]
# schema = layer.schema
pg_layer.CreateFields(schema)
# gdb 不支持fid=0的要素,所以识别到后要+1
offset = 0
f1:Feature = layer.GetNextFeature()
if f1:
if f1.GetFID().__eq__(0):
offset = 1
layer.ResetReading()
count = 0
for feature in layer:
feature.SetFID(feature.GetFID()+offset)
pg_layer.CreateFeature(feature)
count += 1
if count % 10000 == 0:
StructurePrint().print("{}图层已下载{}个对象".format(table_name, count))
gdb_ds.Destroy()
ZipUtil.create_zip(gdb_path + ".zip", [gdb_path])
data.append({"name": ",".join(table_names), "download_url": "http://" + configure.deploy_ip_host + "/API/IO/Download/{}/{}".format(uuid_,table_names[0]+".gdb" + ".zip")})
return data
def msg(self):
pass
api_doc={
"tags":["IO接口"],
"description":"下载数据",
"parameters":[
{"name": "table_name",
"in": "formData",
"type":"string","description":"支持多图层下载,以逗号相隔","required":"true"},
# {"name": "encoding",
# "in": "formData",
# "type": "string",
# "enum":["GBK","UTF-8"]},
{"name": "download_type",
"in": "formData",
"type": "string",
"enum": ["shp", "gdb"],"required":"true"
},
{"name": "database_guid",
"in": "formData",
"type": "string","required":"true"
},
{"name": "creator",
"in": "formData",
"type": "string"
}
],
"responses":{
200:{
"schema":{
"properties":{
"content":{
"type": "string",
"description": "The name of the user"
}
}
}
}
}
}