-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
164 lines (131 loc) · 4.67 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
# -*- coding: utf-8 -*-
import functools
import os
import time
from uuid import uuid4
import requests
from django.conf import settings
from requests.adapters import HTTPAdapter
from requests.auth import HTTPBasicAuth
from requests.packages.urllib3.util.retry import Retry
from django.utils.text import slugify
from cartoview.app_manager.helpers import create_direcotry
from geonode.geoserver.helpers import (get_store, gs_catalog,
ogc_server_settings)
from geonode.geoserver.helpers import create_geoserver_db_featurestore
from .constants import _temp_dir
DEFAULT_WORKSPACE = settings.DEFAULT_WORKSPACE
def SLUGIFIER(text):
return slugify(text)
def get_new_dir(base_dir=_temp_dir):
rand_str = uuid4().__str__().replace('-', '')[:8]
timestr = time.strftime("%Y/%m/%d/%H/%M/%S")
target = os.path.join(base_dir, timestr, rand_str)
create_direcotry(target)
return target
def get_sld_body(url):
req = requests.get(
url,
auth=HTTPBasicAuth(ogc_server_settings.credentials[0],
ogc_server_settings.credentials[1]))
return req.text
def get_gs_store(storename=None, workspace=DEFAULT_WORKSPACE):
if not storename:
storename = ogc_server_settings.datastore_db.get('NAME', None)
return get_store(gs_catalog, storename, workspace)
def get_store_schema(storename=None):
if not storename:
storename = ogc_server_settings.datastore_db.get('NAME')
store = get_store(gs_catalog, storename, settings.DEFAULT_WORKSPACE)
return store.connection_parameters.get('schema', 'public')
def create_datastore(store_name=None, store_type=None):
if not store_name:
store_name = ogc_server_settings.datastore_db['NAME']
return create_geoserver_db_featurestore(
store_type=store_type, store_name=store_name)
def _psycopg2(conn_str):
try:
import psycopg2
conn = psycopg2.connect(conn_str)
cur = conn.cursor()
cur.execute("SELECT version();")
conn.close()
connected = True
except BaseException:
connected = False
return connected
def _django_connection():
try:
from django.db import connections
ds_conn_name = ogc_server_settings.server.get('DATASTORE', None)
conn = connections[ds_conn_name]
conn.connect()
cur = conn.cursor()
cur.execute("SELECT version();")
conn.close()
connected = True
except BaseException:
connected = False
return connected
def requests_retry_session(retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
session=None):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
method_whitelist=frozenset(['GET', 'POST', 'PUT', 'DELETE', 'HEAD']))
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def describe_feature_type(typename):
username = ogc_server_settings.credentials[0]
password = ogc_server_settings.credentials[1]
geoserver_url = ogc_server_settings.LOCATION
s = requests.Session()
s.auth = (username, password)
params = {
'service': 'wfs',
'version': '1.1.0',
'request': 'DescribeFeatureType',
'typeNames': typename,
'outputFormat': 'application/json'
}
from .helpers import urljoin
s = requests_retry_session(session=s)
response = s.get(urljoin(geoserver_url, 'wfs'), params=params)
return response
def get_geom_attr(typename):
response = describe_feature_type(typename)
if response.status_code != 200:
return None
data = response.json()
feature_type = data.get('featureTypes')[0]
properties = feature_type.get('properties')
def is_geom_attr(attr):
if 'gml:' in attr.get('type', ''):
return True
return False
geom_attrs = filter(is_geom_attr, properties)
if len(geom_attrs) == 0:
return None
return str(geom_attrs[0].get('name'))
def repeat_every(repeats=5, every=2):
"""
decorator evaluates function after maximum number of repeats every number of seconds
"""
def repeat_wrapper(func):
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
for _ in range(repeats):
value = func(*args, **kwargs)
if value:
return value
time.sleep(every)
return func_wrapper
return repeat_wrapper