-
Notifications
You must be signed in to change notification settings - Fork 1
/
style_manager.py
194 lines (168 loc) · 6.62 KB
/
style_manager.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
# -*- coding: utf-8 -*-
import time
from contextlib import contextmanager
from io import BytesIO
import lxml
from django.conf import settings
from geonode.geoserver.helpers import gs_catalog
from geonode.layers.models import Style
from .helpers import unicode_converter
from .utils import SLUGIFIER, repeat_every
try:
import _sqlite3 as sqlite3
except ImportError:
import sqlite3
class LayerStyle(object):
def __init__(self, *args, **kwargs):
for key in kwargs:
setattr(self, key, kwargs[key])
@staticmethod
def get_attribute_names():
attrs = []
for name in vars(LayerStyle):
if name.startswith("__"):
continue
attr = getattr(LayerStyle, name)
if callable(attr):
continue
attrs.append(name)
return attrs
def as_dict(self):
return {
attr: getattr(self, attr)
for attr in self.get_attribute_names()
}
class StyleManager(object):
styles_table_name = 'layer_styles'
def __init__(self, gpkg_path):
self.db_path = gpkg_path
@contextmanager
def db_session(self, row_factory=True):
conn = sqlite3.connect(self.db_path)
if row_factory:
conn.row_factory = lambda c, r: dict(
[(col[0], r[idx]) for idx, col in enumerate(c.description)])
yield conn
conn.close()
def upload_style(self, style_name, sld_body, overwrite=False):
name = self.get_new_name(style_name)
gs_catalog.create_style(
name,
sld_body,
overwrite=overwrite,
raw=True,
workspace=settings.DEFAULT_WORKSPACE)
style_func = repeat_every()(gs_catalog.get_style)
style = style_func(name, settings.DEFAULT_WORKSPACE)
style_url = style.body_href
gstyle, created = Style.objects.get_or_create(
name=name,
sld_title=name,
workspace=settings.DEFAULT_WORKSPACE,
sld_body=sld_body,
sld_url=style_url)
return gstyle
def set_default_layer_style(self, layername, stylename):
gs_layer = gs_catalog.get_layer(layername)
gs_layer.default_style = gs_catalog.get_style(
stylename, workspace=settings.DEFAULT_WORKSPACE)
gs_catalog.save(gs_layer)
def get_new_name(self, sld_name):
sld_name = SLUGIFIER(sld_name)
style = gs_catalog.get_style(
sld_name, workspace=settings.DEFAULT_WORKSPACE)
if not style:
return sld_name
else:
timestr = time.strftime("%Y%m%d_%H%M%S")
return "{}_{}".format(sld_name, timestr)
def table_exists_decorator(failure_result=None):
def wrapper(function):
def wrapped(*args, **kwargs):
this = args[0]
if this.check_styles_table_exists():
return function(*args, **kwargs)
return failure_result
return wrapped
return wrapper
def check_styles_table_exists(self):
check = 0
with self.db_session(row_factory=False) as session:
cursor = session.cursor()
cursor.execute(
"""SELECT count(*) FROM sqlite_master \
WHERE type="table" AND name=?""", (self.styles_table_name, ))
result = cursor.fetchone()
check = result[0]
return check
@staticmethod
def from_row(row):
return LayerStyle(**unicode_converter(row))
@table_exists_decorator(failure_result=[])
def get_styles(self):
with self.db_session() as session:
cursor = session.cursor()
cursor.execute('select * from {}'.format(self.styles_table_name))
rows = cursor.fetchall()
styles = [self.from_row(row) for row in rows]
return styles
def create_table(self):
if not self.check_styles_table_exists():
with self.db_session() as session:
cursor = session.cursor()
cursor.execute('''
CREATE TABLE {} (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`f_table_catalog` TEXT ( 256 ),
`f_table_schema` TEXT ( 256 ),
`f_table_name` TEXT ( 256 ),
`f_geometry_column` TEXT ( 256 ),
`styleName` TEXT ( 30 ),
`styleQML` TEXT,
`styleSLD` TEXT,
`useAsDefault` BOOLEAN,
`description` TEXT,
`owner` TEXT ( 30 ),
`ui` TEXT ( 30 ),
`update_time` DATETIME DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
);'''.format(self.styles_table_name))
session.commit()
@table_exists_decorator(failure_result=None)
def get_style(self, layername):
with self.db_session() as session:
cursor = session.cursor()
cursor.execute(
'SELECT * FROM {} WHERE f_table_name=?'.format(
self.styles_table_name), (layername, ))
rows = cursor.fetchone()
if rows and len(rows):
return self.from_row(rows)
else:
return None
def convert_sld_attributes(self, sld_body):
contents = BytesIO(str(sld_body))
tree = lxml.etree.parse(contents)
root = tree.getroot()
nsmap = {k: v for k, v in root.nsmap.items() if k}
properties = tree.xpath('.//ogc:PropertyName', namespaces=nsmap)
for prop in properties:
value = str(prop.text).lower()
prop.text = value
return lxml.etree.tostring(tree)
@table_exists_decorator(failure_result=None)
def add_style(self,
layername,
geom_field,
stylename,
sld_body,
default=False):
# sld_body = self.convert_sld_attributes(sld_body)
with self.db_session() as session:
cursor = session.cursor()
cursor.execute(
'INSERT INTO {} (f_table_name,f_geometry_column,styleName,styleSLD,useAsDefault) VALUES (?,?,?,?,?);'.
format(self.styles_table_name),
(layername, geom_field, stylename, sld_body, default))
session.commit()
return cursor.lastrowid
# TODO: add_styles with executemany