-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviews.py
442 lines (360 loc) · 16.4 KB
/
views.py
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import pandas, re, psycopg2, math, unidecode, datetime, requests
import json, os, tempfile
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from GeoExcel.utils import retrieveDatumNames, datumCode, searchTablesByDatabase, createMappingTable, InsertValues, getMappingTable, save_layer, createView, create_table_excel_general, update_layer
from GeoExcel.helpers import convertToKnownDatatype
from General_modules.module_logs import log_error_file, log_logs_file
from General_modules.module_DB import constraintsTable, checkDataType
from General_modules import global_settings
@login_required
def excel_upload(request, template='upload/layer_upload.html'):
"""
Receive a file, saved it on a tmp location, and redirect to this application
"""
out = {'success': False}
if request.method == 'POST':
regex = re.compile(r"^%s$" % 'base_file')
for name, value in request.FILES.items():
match = regex.match(name)
if match:
fileName = '%s'%(value)
excel_data_df = pandas.read_excel(value)
fd, path = tempfile.mkstemp(dir=global_settings.PATH_TMP_FILES)
try:
with os.fdopen(fd, 'w') as tmp:
# do stuff with temp file
excel_data_df.to_csv(tmp, index = None, header=True)
except Exception as e:
log_error_file(str(e))
finally:
tmp.close()
status_code = 200
out['success'] = True
out['typeFile'] = path
out['redirect'] = reverse('excel_begin')
out['fileName'] = fileName
break
else:
# Não recebeu um excel da maneira correta
status_code = 400
else:
status_code = 400
return HttpResponse(
json.dumps(out),
content_type='application/json',
status=status_code)
@login_required
def excel_begin(request, template='GeoExcel/excel_begin.html', template_error='GeoExcel/error_page.html'):
"""
Create the conditions for a user to choose between create a new table or add information to a existent table
"""
rec = searchTablesByDatabase(global_settings.GENERIC_SAVE_EXCEL_DB, global_settings.POSTGRESQL_USERNAME, global_settings.POSTGRESQL_PASSWORD, global_settings.POSTGRESQL_HOST, global_settings.POSTGRESQL_PORT, True)
if not rec['success']:
return render(request, template_error,{
"action":reverse('layer_upload'),
"error": "%s"%(rec['data'])
})
fileName = request.POST['fileName']
path = request.POST['path']
return render(request,template, context={
"path":path,
"action_add":reverse('addNewEntries'),
"action_create":reverse('configureTable'),
"tables":rec['data'],
"fileName":fileName
})
@login_required
def configureTable(request, template='GeoExcel/excel_create.html', template_error='GeoExcel/error_page.html'):
"""
Create the conditions for the user create is on table, by choosing the primary and foreing keys, also to create a new variable that is related with geographical locations
"""
path = ''
fileName = ''
cols=[]
datumName=[]
columns = None
if request.method == 'POST':
path = request.POST['path']
fileName = request.POST['fileName']
tableName = request.POST['tableName']
db_user = global_settings.POSTGRESQL_USERNAME
db_password = global_settings.POSTGRESQL_PASSWORD
db_host = global_settings.POSTGRESQL_HOST
db_port = global_settings.POSTGRESQL_PORT
if tableName == '' or path == '' or fileName == '':
return render(request, template_error,{
"action":reverse('layer_upload'),
"error": "One of the inputs is None"
})
tables_database_dict = searchTablesByDatabase(global_settings.GENERIC_SAVE_EXCEL_DB, db_user, db_password, db_host, db_port)
if tables_database_dict['success']:
if tableName in tables_database_dict['data']:
return render(request, template_error,{
"action": reverse('layer_upload'),
"error": "Table {} already exists".format(tableName)
})
data_df = pandas.read_csv(path)
columns = data_df.columns.ravel()
for i in columns:
cols.append(i)
datum = retrieveDatumNames("epsg", db_user, db_password, db_host, db_port)
if datum['success']:
datumName = datum['data']
else :
return render(request, template_error,{
"action":reverse('layer_upload'),
"error": "%s"%(datum['data'])
})
return render(request,template, context={
"path":path,
'columns': cols,
"action":"submit",
"fileName":fileName,
"tableName":tableName,
"datum":datumName,
"path_search_tables":reverse('searchTables'),
"path_search_tablekey":reverse('searchTableKey'),
})
@login_required
def searchTables(request, template='GeoExcel/error_page.html'):
"""
Get all tables that exist on a database
"""
out = {'success': False}
status_code = 400
if request.method == 'GET':
rec = searchTablesByDatabase(global_settings.GENERIC_SAVE_EXCEL_DB, global_settings.POSTGRESQL_USERNAME, global_settings.POSTGRESQL_PASSWORD, global_settings.POSTGRESQL_HOST, global_settings.POSTGRESQL_PORT)
if rec['success']:
status_code = 200
out['success'] = True
out['tables'] = rec['data']
else:
out['error'] = str(rec['data'])
return HttpResponse(
json.dumps(out),
content_type='application/json',
status=status_code)
@login_required
def searchTableKey(request, template='GeoExcel/error_page.html'):
"""
Get all the primary or unique keys for a specific table
"""
out = {'success': False}
status_code = 400
if request.method == 'GET':
constraints =['PRIMARY KEY', 'UNIQUE']
cols=[]
dataType = []
Database = global_settings.GENERIC_SAVE_EXCEL_DB
db_user = global_settings.POSTGRESQL_USERNAME
db_password = global_settings.POSTGRESQL_PASSWORD
db_host = global_settings.POSTGRESQL_HOST
db_port = global_settings.POSTGRESQL_PORT
for const in constraints:
check = constraintsTable(request.GET['tableName'], const, Database, db_user, db_password, db_host, db_port)
if check['success']:
for data in check['data']:
cols.append(list(data)[0])
else:
out['error'] = str(check['data'])
return HttpResponse(
json.dumps(out),
content_type='application/json',
status=status_code)
for col in cols:
check = checkDataType(request.GET['tableName'], col, Database, db_user, db_password, db_host, db_port)
if check['success']:
for data in check['data']:
dataType.append(convertToKnownDatatype(list(data)[0]))
else:
out['error'] = str(check['data'])
return HttpResponse(
json.dumps(out),
content_type='application/json',
status=status_code)
out['colname'] = cols
out['datatype'] = dataType
status_code = 200
out['success'] = True
return HttpResponse(
json.dumps(out),
content_type='application/json',
status=status_code)
@login_required
def submitTable(request, template='GeoExcel/error_page.html'):
"""
Convert the excel to a table form and upload to the database
"""
if request.method == 'POST':
coordenatePoints = False
data_UI = request.POST
keys = {}
path = data_UI['path']
tableName = data_UI['tableName']
foreignKeys = int(data_UI['foreignKeys'])
foreignData = {}
data_dataframe = pandas.read_csv(path)
columns = data_dataframe.columns.ravel()
Database = global_settings.GENERIC_SAVE_EXCEL_DB
db_user = global_settings.POSTGRESQL_USERNAME
db_password = global_settings.POSTGRESQL_PASSWORD
db_host = global_settings.POSTGRESQL_HOST
db_port = global_settings.POSTGRESQL_PORT
if tableName == '' or path == '':
return render(request, template,{
"action":reverse('layer_upload'),
"error": "One of the inputs is None"
})
tables_database_dict = searchTablesByDatabase(global_settings.GENERIC_SAVE_EXCEL_DB, db_user, db_password, db_host, db_port)
if tables_database_dict['success']:
if tableName in tables_database_dict['data']:
return render(request, template,{
"action": reverse('layer_upload'),
"error": "Table {} already exists".format(tableName)
})
if ('None' != data_UI['latName'] and 'None' == data_UI['longName']) or ('None' == data_UI['latName'] and 'None' != data_UI['longName']):
return render(request, template,{
"action":reverse('layer_upload'),
"error": "One of the fields of the 1st Step is None while the other field is not None"
})
datum_code = '4326'
if data_UI['datum'] != 'None':
datum=datumCode(data_UI['datum'], "epsg", db_user, db_password, db_host, db_port)
if datum['success']:
datum_code=datum['data']
for i in range(1,foreignKeys+1):
if ( not (data_UI['column3Step%s'%(i)] != 'None' and data_UI['tableForeign%s'%(i)] != 'None' and data_UI['columnForeign%s'%(i)] != 'None')) and \
( not (data_UI['column3Step%s'%(i)] == 'None' and data_UI['tableForeign%s'%(i)] == 'None' and data_UI['columnForeign%s'%(i)] == 'None')):
return render(request, template,{
"action":reverse('layer_upload'),
"error": "One of the fields of the 3st Step is None while the other field is not None"
})
if('None' != data_UI['latName'] and 'None' != data_UI['longName']):
coordenatePoints = True
# Make a dicitionary that contains the information about the foreign keys, also if there is a misunderstanding it gives an error
for i in range(1,foreignKeys+1):
if (data_UI['column3Step%s'%(i)] == 'None' or data_UI['tableForeign%s'%(i)] == 'None' or data_UI['columnForeign%s'%(i)] == 'None' or data_UI['dataType%s'%(i)] == 'None'):
continue
# Se só quisermos que uma coluna só tenha uma foreign key
if data_UI['column3Step%s'%(i)] in foreignData.keys():
return render(request, template,{
"action":reverse('layer_upload'),
"error": "Choose the same column to be multiple column "
})
else:
foreignData[data_UI['column3Step%s'%(i)]] = {
'type':data_UI['dataType%s'%(i)],
'table':data_UI['tableForeign%s'%(i)],
'column':data_UI['columnForeign%s'%(i)]
}
#Creating table as per requirement
resp_sql, foreignOptions, timeDimesionAttr, error_msg = create_table_excel_general(tableName, columns, data_dataframe, keys, data_UI, coordenatePoints, datum_code, foreignData, Database, db_user, db_password, db_host, db_port)
if error_msg != "":
return render(request, template,{
"action":reverse('layer_upload'),
"error": error_msg
})
if not resp_sql['success']:
error_msg = 'Error Creating Table: {}'.format(resp_sql['data'])
log_logs_file(error_msg)
return render(request, template,{
"action":reverse('layer_upload'),
"error": error_msg
})
if len(foreignOptions) > 0:
tableView = createView(Database, db_user, db_password, db_host, db_port, foreignOptions)
else:
tableView = 'None'
resp_sql = createMappingTable(data_UI, tableName, coordenatePoints, columns, foreignData, datum_code, tableView, Database, db_user, db_password, db_host, db_port)
if not resp_sql['success']:
error_msg = 'Error Insert Values: {}'.format(resp_sql['data'])
log_logs_file(error_msg)
return render(request, template,{
"action":reverse('layer_upload'),
"error": error_msg
})
resp_sql = InsertValues(path, keys, data_UI, coordenatePoints, datum_code, tableName, Database, db_user, db_password, db_host, db_port, foreignData)
if resp_sql is None :
error_msg = 'Error Insert Values: SQL is empty for some reason.'
log_logs_file(error_msg)
error_msg += '\nCaution: Check if the data type is chosen correctly.'
return render(request, template,{
"action":reverse('layer_upload'),
"error": error_msg
})
if not resp_sql['success']:
error_msg = 'Error Insert Values: {}'.format(resp_sql['data'])
log_logs_file(error_msg)
return render(request, template,{
"action":reverse('layer_upload'),
"error": error_msg
})
#Remove the tmp file
os.remove(path)
if tableView == 'None':
save_layer(tableName, timeDimesionAttr)
else:
save_layer(tableView, timeDimesionAttr)
return redirect('layer_upload')
return render(request, template,{
"action":reverse('layer_upload'),
"error": "Wrong method to access %s"%(reverse('submitTable'))
})
@login_required
def addNewEntries(request, template='GeoExcel/error_page.html'):
"""
ADD new entries to a specific table
"""
if request.method == 'POST':
Database = global_settings.GENERIC_SAVE_EXCEL_DB
db_user = global_settings.POSTGRESQL_USERNAME
db_password = global_settings.POSTGRESQL_PASSWORD
db_host = global_settings.POSTGRESQL_HOST
db_port = global_settings.POSTGRESQL_PORT
path = request.POST['path']
tableName = request.POST['tableName']
rec = getMappingTable(Database, db_user, db_password, db_host, db_port, tableName)
if not rec['success']:
return render(request, template,{
"action":reverse('layer_upload'),
"error": "%s"%(rec['data'])
})
mapping = rec['data']
data_df = pandas.read_csv(path)
columns = data_df.columns.ravel()
data = mapping['variables']
data.update(mapping['coordenateInfo'])
keys = {}
if mapping['coordenatePoints']:
datum_code = data["datum"]
data[data['latName']] = 'None'
data[data['longName']] = 'None'
keys['coord'] = data['colName']
location_col_name = data['colName']
else:
datum_code = 0
location_col_name = None
for name in columns:
if mapping['coordenatePoints']:
if name == data['latName'] or name == data['longName']:
continue
keys[name] = name
resp_sql = InsertValues(path, keys, data, mapping['coordenatePoints'], datum_code, tableName, Database, db_user, db_password, db_host, db_port)
update_layer(tableName, location_col_name)
#Remove the tmp file
os.remove(path)
if not resp_sql['success']:
error_msg = 'Error Insert Values: {}'.format(resp_sql['data'])
log_logs_file(error_msg)
return render(request, template,{
"action":reverse('layer_upload'),
"error": error_msg
})
return redirect('layer_upload')
return render(request, template, {
"action":reverse('layer_upload'),
"error": "Wrong method to access %s"%(reverse('addNewEntries'))
})