forked from its4land/qgis-boundary-delineation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Its4landAPI.py
256 lines (200 loc) · 8.61 KB
/
Its4landAPI.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
"""API integration with its4land project.
Attributes:
DEBUG (bool): is debug enabled (logs the whole communication)
Payload (TYPE): the payload sent to server
Notes:
begin : 2019-04-14
git sha : $Format:%H$
development : 2019, Ivan Ivanov @ ITC, University of Twente
email : [email protected]
copyright : (C) 2019 by Ivan Ivanov
License:
MIT License
Copyright (c) 2020 "its4land project", "ITC, University of Twente"
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from typing import Any, Optional, Dict
from enum import Enum
from urllib.parse import urljoin, quote
from requests import request, exceptions
DEBUG = False
if DEBUG:
import logging
# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
import http.client as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
class ResponseType(Enum):
json = 1
text = 2
html = 3
stream = 4
Payload = Dict[str, Any]
class Its4landException(Exception):
def __init__(
self,
msg: str = None,
error: exceptions.RequestException = None,
url: str = None,
code: int = None
):
self.msg = msg
self.code = code
self.url = url
self.error = error
self.count = 0
if error:
if isinstance(error, Its4landException):
self.msg = msg or error.msg
self.code = code or error.code
self.url = url or error.url
self.count = error.count + 1
elif isinstance(error, exceptions.RequestException):
self.msg = msg or str(error)
else:
self.msg = msg or str(error)
if 'response' in error:
self.code = error.response.code
self.url = error.response.url
else:
self.code = code
self.url = url
else:
self.msg = msg
self.code = code
self.url = url
super().__init__(self.msg)
class Its4landAPI:
def __init__(self, url: str, api_key: str, response_type: ResponseType = ResponseType.json):
self.url = url + '/'
self.api_key = api_key
self.response_type = response_type
self.session_token = ''
def get(self, *argv, **kwargs):
return self.request('GET', *argv, **kwargs)
def post(self, *argv, **kwargs):
return self.request('POST', *argv, **kwargs)
def patch(self, *argv, **kwargs):
return self.request('PATCH', *argv, **kwargs)
def request(self,
method: str,
data: Optional[Payload],
encode_as: str = 'form',
response_type: ResponseType = None,
files: Dict[str, Any] = None,
headers: Dict[str, str] = dict(),
auth_required: bool = True,
url: str = None):
url = url or self.url
response_type = response_type or self.response_type
assert not auth_required or self.session_token, 'No session token provided'
try:
headers['X-Api-Key'] = self.api_key
if self.session_token:
headers['X-Session-Token'] = self.session_token
send_data: Dict[str, Any] = {
'stream': (response_type == ResponseType.stream),
'headers': headers,
}
if method == 'GET':
send_data['params'] = data
else:
if encode_as == 'json':
send_data['json'] = data
elif encode_as == 'form':
send_data['data'] = data
else:
raise Exception(url, 998, 'Unknown encode type: %s' % encode_as)
if files is not None and len(files):
send_data['files'] = {}
for k, v in files.items():
try:
send_data['files'][k] = open(v, 'rb')
except Exception as e:
raise Exception(url, 998, 'Unable to open file: %s' % v, e)
resp = request(method, url, **send_data)
if DEBUG:
import curlify
print(curlify.to_curl(resp.request))
if resp is not None:
if resp.ok and resp.content is not None:
if response_type == ResponseType.stream:
return resp
elif response_type == ResponseType.json:
return resp.json()
elif response_type == ResponseType.html:
return resp.content
assert False, 'Unrecognized response type'
else:
raise Its4landException(url=resp.url, code=resp.status_code, msg=resp.reason)
else:
raise Its4landException(url=url, msg='There is no response, something bad happened')
except exceptions.RequestException as e:
raise Its4landException(error=e)
except Exception as e:
raise Its4landException(url=url, error=e)
def login(self, login: str, password: str) -> str:
# self.session_token = self.post({
# 'login': login,
# 'password': password,
# },
# auth_required=False,
# url=urljoin(self.url, 'login'))
self.session_token = 'SESSION_TOKEN'
return self.session_token
def get_projects(self):
return self.get(None, url=urljoin(self.url, 'projects'))
def get_validation_sets(self, project_id: str):
return self.get({
'projects': project_id
}, url=urljoin(self.url, 'WP5ValidationSets'))
def get_boundary_strings(self, project_id: str):
return self.get({
'projects': project_id
}, url=urljoin(self.url, 'boundaryfacestring'))
def post_boundary_strings(self, geojson: str):
url = urljoin(self.url, 'boundaryfacestring')
return self.post(geojson, url=url, encode_as='json')
def patch_boundary_strings(self, project_id: str, geojson: str):
url = urljoin(self.url, 'boundaryfacestring/%s' % quote(project_id, safe=''))
return self.patch(geojson, url=url, encode_as='json')
def get_content_item(self, uid: str):
return self.get({
'uid': uid
}, url=urljoin(self.url, 'contentitems'))
def get_base_layers(self, project_id: str):
return self.get({
'projects': project_id,
}, url=urljoin(self.url, 'DDILayers'))
def download_content_item(self, uid: str, filename: str):
url = urljoin(self.url, 'contentitems/%s' % quote(uid, safe=''))
return self.download_file(None, url=url, filename=filename)
def download_file(self, data: Optional[Payload], filename: str, **rest) -> str:
resp = self.get(data, response_type=ResponseType.stream, **rest)
with open(filename, 'wb') as f:
for chunk in resp.iter_content(chunk_size=4096):
if not chunk: # filter out keep-alive new chunks
pass
f.write(chunk)
return filename