/
utils.py
298 lines (241 loc) · 10 KB
/
utils.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
# -*- coding: utf-8 -*-
'''
gvSIG Online.
Copyright (C) 2010-2017 SCOLAB.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
'''
@author: Javier Rodrigo <jrodrigo@scolab.es>
'''
import json
import os
from string import strip
from django.http.response import HttpResponse
import psycopg2
import geographic_servers
from gvsigol import settings
from gvsigol.settings import MEDIA_ROOT
from gvsigol_auth.models import UserGroup
from gvsigol_services.models import Datastore, LayerResource, \
LayerFieldEnumeration, EnumerationItem, Enumeration, Layer, LayerGroup
from models import LayerReadGroup, LayerWriteGroup
def get_all_user_groups_checked_by_layer(layer):
groups_list = UserGroup.objects.all()
read_groups = LayerReadGroup.objects.filter(layer=layer)
write_groups = LayerWriteGroup.objects.filter(layer=layer)
groups = []
for g in groups_list:
if g.name != 'admin' and g.name != 'public':
group = {}
for lrg in read_groups:
if lrg.group_id == g.id:
group['read_checked'] = True
for lwg in write_groups:
if lwg.group_id == g.id:
group['write_checked'] = True
group['id'] = g.id
group['name'] = g.name
group['description'] = g.description
groups.append(group)
return groups
def get_read_roles(layer):
roles = []
layer_read_groups = LayerReadGroup.objects.filter(layer_id=layer.id)
for layer_read_group in layer_read_groups:
group = UserGroup.objects.get(id=layer_read_group.group_id)
roles.append(group.name)
return roles
def get_write_roles(layer):
roles = []
layer_write_groups = LayerWriteGroup.objects.filter(layer_id=layer.id)
for layer_write_group in layer_write_groups:
group = UserGroup.objects.get(id=layer_write_group.group_id)
roles.append(group.name)
return roles
#TODO: llevar al paquete del core
def create_datastore(request, username, ds_name, ws):
ds_type = 'v_PostGIS'
description = 'BBDD ' + ds_name
dbhost = settings.GVSIGOL_USERS_CARTODB['dbhost']
dbport = settings.GVSIGOL_USERS_CARTODB['dbport']
dbname = settings.GVSIGOL_USERS_CARTODB['dbname']
dbuser = settings.GVSIGOL_USERS_CARTODB['dbuser']
dbpassword = settings.GVSIGOL_USERS_CARTODB['dbpassword']
connection_params = '{ "host": "' + dbhost + '", "port": "' + dbport + '", "database": "' + dbname + '", "schema": "' + ds_name + '", "user": "' + dbuser + '", "passwd": "' + dbpassword + '", "dbtype": "postgis" }'
if create_schema(ds_name):
gs = geographic_servers.get_instance().get_server_by_id(ws.server.id)
if gs.createDatastore(ws, ds_type, ds_name, description, connection_params):
# save it on DB if successfully created
datastore = Datastore(
workspace = ws,
type = ds_type,
name = ds_name,
description = description,
connection_params = connection_params,
created_by=username
)
datastore.save()
return datastore
#TODO: llevar al paquete del core
def create_schema(ds_name):
dbhost = settings.GVSIGOL_USERS_CARTODB['dbhost']
dbport = settings.GVSIGOL_USERS_CARTODB['dbport']
dbname = settings.GVSIGOL_USERS_CARTODB['dbname']
dbuser = settings.GVSIGOL_USERS_CARTODB['dbuser']
dbpassword = settings.GVSIGOL_USERS_CARTODB['dbpassword']
connection = get_connection(dbhost, dbport, dbname, dbuser, dbpassword)
cursor = connection.cursor()
try:
create_schema = "CREATE SCHEMA IF NOT EXISTS " + ds_name + " AUTHORIZATION " + dbuser + ";"
cursor.execute(create_schema)
except StandardError, e:
print "SQL Error", e
if e.pgcode == '42710':
return True
else:
return False
close_connection(cursor, connection)
return True
#TODO: llevar al paquete del core
def get_connection(host, port, database, user, password):
try:
conn = psycopg2.connect("host=" + host +" port=" + port +" dbname=" + database +" user=" + user +" password="+ password);
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
print "Connect ... "
except StandardError, e:
print "Failed to connect!", e
return []
return conn;
def get_distinct_query(host, port, schema, database, user, password, layer, field, where=None):
values = []
conn = get_connection(host, port, database, user, password)
cursor = conn.cursor()
where_query = ''
if where:
where_query = " " + str(where) + " "
try:
sql = 'SELECT DISTINCT("' + field + '") FROM ' + schema + '.' + layer + where_query + ' ORDER BY "' + field + '" ASC;'
cursor.execute(sql);
rows = cursor.fetchall()
for row in rows:
if row[0] is not None:
val = row[0]
if isinstance(val, basestring):
values.append(val)
else:
val = str(val)
values.append(val)
except StandardError, e:
print "Query error!", e
return []
close_connection(cursor, conn)
return values
def get_minmax_query(host, port, schema, database, user, password, layer, field):
conn = get_connection(host, port, database, user, password)
cursor = conn.cursor()
try:
sql = 'SELECT MIN("' + field + '") AS MinValue, MAX("' + field + '") AS MaxValue FROM ' + schema + '.' + layer + ' WHERE "' + field + '" IS NOT NULL;'
cursor.execute(sql);
rows = cursor.fetchall()
except StandardError, e:
print "Fallo en el getMIN y getMAX", e
return {}
close_connection(cursor, conn)
if len(rows) > 0:
minmax = rows[0]
if len(minmax) == 2:
min = minmax[0]
max = minmax[1]
return json.dumps({'min': float(min), 'max': float(max)})
return {}
#TODO: llevar al paquete del core
def close_connection(cursor, conn):
#Close connection and exit
cursor.close();
conn.close();
def get_fields(resource):
fields = None
if resource != None:
fields = resource.get('featureType').get('attributes').get('attribute')
return fields
def get_alphanumeric_fields(fields):
alphanumeric_fields = []
for field in fields:
if not 'jts.geom' in field.get('binding'):
alphanumeric_fields.append(field)
return alphanumeric_fields
def get_resources_dir(resource_type):
if resource_type == LayerResource.EXTERNAL_IMAGE:
the_path = os.path.join(MEDIA_ROOT, "resources/image")
elif resource_type == LayerResource.EXTERNAL_PDF:
the_path = os.path.join(MEDIA_ROOT, "resources/pdf")
elif resource_type == LayerResource.EXTERNAL_DOC:
the_path = os.path.join(MEDIA_ROOT, "resources/docs")
elif resource_type == LayerResource.EXTERNAL_VIDEO:
the_path = os.path.join(MEDIA_ROOT, "resources/videos")
else:
the_path = os.path.join(MEDIA_ROOT, "resources/files")
if not os.path.exists(the_path):
os.makedirs(the_path, 0700)
return the_path
def get_resource_type(lr):
url = None
type = None
if lr.type == LayerResource.EXTERNAL_IMAGE:
type = 'image'
url = os.path.join(settings.MEDIA_URL, lr.path)
elif lr.type == LayerResource.EXTERNAL_PDF:
type = 'pdf'
url = os.path.join(settings.MEDIA_URL, lr.path)
elif lr.type == LayerResource.EXTERNAL_DOC:
type = 'doc'
url = os.path.join(settings.MEDIA_URL, lr.path)
elif lr.type == LayerResource.EXTERNAL_FILE:
type = 'file'
url = os.path.join(settings.MEDIA_URL, lr.path)
elif lr.type == LayerResource.EXTERNAL_VIDEO:
type = 'video'
url = os.path.join(settings.MEDIA_URL, lr.path)
elif lr.type == LayerResource.EXTERNAL_ALFRESCO_DIR:
type = 'alfresco_dir'
url = lr.path
return [type, url]
def is_field_enumerated(column_name, table_name, datastore):
"""
Returns true if the field is enumerated and false if not. The second parameter is true if the enumeration is multiple
"""
enums = LayerFieldEnumeration.objects.filter(layername=table_name, schema=datastore, field=column_name)
if len(enums) > 0:
return True, enums[0].multiple
return False, False
def get_enum_item_list(column_name, lyr_name, workspace_name):
"""
Gets the list of items of a enumerated field
"""
lyr_obj = Layer.objects.get(name=lyr_name, datastore__workspace__name=workspace_name)
if(lyr_obj is not None):
enums = LayerFieldEnumeration.objects.filter(layername=lyr_name, schema=lyr_obj.datastore.name, field=column_name)
if len(enums) > 0:
return EnumerationItem.objects.filter(enumeration_id=enums[0].enumeration_id)
def get_enum_entry(column_name, lyr_name, workspace_name):
"""
Gets the list of items of a enumerated field
"""
lyr_obj = Layer.objects.get(name=lyr_name, datastore__workspace__name=workspace_name)
if(lyr_obj is not None):
enums = LayerFieldEnumeration.objects.filter(layername=lyr_name, schema=lyr_obj.datastore.name, field=column_name)
if len(enums) > 0:
return Enumeration.objects.get(id=enums[0].enumeration_id)
def get_exception(code, msg):
response = HttpResponse(msg)
response.status_code = code
return response