source: src/mapservice/server_impl/database/Model.py@ 7be94aa

debian/bullseye
Last change on this file since 7be94aa was 7be94aa, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
  • Property mode set to 100644
File size: 16.2 KB
Line 
1'''
2 Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16'''
17import flask
18from flask_sqlalchemy import SQLAlchemy
19from sqlalchemy import inspect, text, Enum, event, select, func
20from sqlalchemy.orm.attributes import get_history
21from geoalchemy2 import Geometry
22from geoalchemy2.shape import to_shape
23from sqlalchemy_utc import UtcDateTime
24from sqlalchemy_utils import create_view, database_exists, create_database
25import hashlib
26import datetime
27import enum
28import connexion
29from pathlib import Path
30import sys
31import os
32
33db = SQLAlchemy()
34
35
36class OsmType(enum.Enum):
37 Node = 1
38 Way = 2
39 Relation = 3
40
41
42def wkb_to_dict(wkbelement):
43 point = to_shape(wkbelement)
44 return {'longitude': point.x, 'latitude': point.y}
45
46
47class User(db.Model):
48 __tablename__ = "users"
49
50 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
51 username = db.Column(db.String(255), nullable=False, unique=True)
52 password = db.Column(db.String(50), nullable=False)
53 salt = db.Column(db.String(50), nullable=False)
54 email = db.Column(db.String(255), nullable=False)
55 first_name = db.Column(db.String(255))
56 last_name = db.Column(db.String(255))
57 activated = db.Column(db.Boolean(), default=False)
58 activation_code = db.Column(db.String(255), default='1234')
59 #activation_code = db.Column(db.String(255), server_default=text('LEFT(MD5(NOW()), 50)'))
60 license_accepted = db.Column(db.Boolean(), default=False)
61
62 def to_dict(user):
63 result = {
64 'username': user.username,
65 'password': user.password,
66 'salt': user.salt,
67 'email': user.email,
68 'firstName': "",
69 'lastName': "",
70 'activated': user.activated,
71 'licenseAccepted': user.license_accepted
72 }
73 if user.first_name is not None:
74 result['firstName'] = user.first_name
75 if user.last_name is not None:
76 result['lastName'] = user.last_name
77 if user.activation_code is not None:
78 result['activationCode'] = user.activation_code
79
80 return result
81
82 def factory(username, password, email):
83 salt = hashlib.md5(
84 '{}{}'.format(
85 username,
86 datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
87 ).encode()
88 ).hexdigest()
89 password = hashlib.md5('{}{}'.format(password,
90 salt).encode()).hexdigest()
91 activation_code = hashlib.md5(
92 '{}'.format(datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')
93 ).encode()
94 ).hexdigest()
95 return User(
96 username=username,
97 password=password,
98 email=email,
99 salt=salt,
100 activated=False,
101 activation_code=activation_code
102 )
103
104 def password_verify(self, password):
105 return hashlib.md5("{}{}".format(password, self.salt).encode()
106 ).hexdigest() == self.password
107
108 @staticmethod
109 def loggedin_username():
110 if not 'user' in connexion.context:
111 return None
112 return connexion.context['user']
113
114 @staticmethod
115 def loggedin_user():
116 username = User.loggedin_username()
117 if username is None:
118 return None
119 user = User.query.filter_by(username=username).all()
120 if len(user) != 1:
121 return None
122 return user[0]
123
124
125class ApiKey(db.Model):
126 __tablename__ = "apikeys"
127
128 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
129 user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'))
130 key = db.Column(db.String(255), nullable=False, unique=True)
131 user = db.relationship("User", backref=db.backref("apikeys"), lazy=True)
132
133
134class Water(db.Model):
135 __tablename__ = "waters"
136
137 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
138 name = db.Column(db.String(255), nullable=False)
139 manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
140 osm_id = db.Column(db.Integer)
141 osm_type = db.Column(Enum(OsmType))
142 manager = db.relationship("User", backref=db.backref("waters"), lazy=True)
143
144 def to_dict(obj):
145 result = {'waterId': obj.id, 'name': obj.name}
146 if obj.manager:
147 result['manager'] = obj.manager.username
148 if obj.osm_id:
149 result['osmId'] = obj.osm_id
150 if obj.osm_type:
151 result['osmType'] = obj.osm_type.name
152 if obj.gauges:
153 result['gauges'] = []
154 for gauge in obj.gauges:
155 result['gauges'].append(gauge.to_dict())
156 if obj.logs:
157 logs = []
158 for log in obj.logs:
159 logs.append(log.meta_data())
160 result['logs'] = logs
161 return result
162
163
164class Gauge(db.Model):
165 __tablename__ = "gauges"
166
167 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
168 name = db.Column(db.String(255), nullable=False)
169 manager_id = db.Column(db.Integer, db.ForeignKey('users.id'))
170 water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
171 # POINT(Lon Lat)
172 location = db.Column(
173 Geometry(geometry_type='POINT', srid=4326, management=True)
174 )
175 reference_water_level_gauge_height = db.Column(db.Float, nullable=False)
176 comment = db.Column(db.String(255))
177 #osm_id = db.Column(db.Integer)
178 #osm_type = db.Column(db.String(255))
179 #osm_class = db.Column(db.String(255))
180 manager = db.relationship("User", backref=db.backref("gauges"), lazy=True)
181 water = db.relationship("Water", backref=db.backref("gauges"), lazy=True)
182
183 def to_dict(obj):
184 result = {'gaugeId': obj.id, 'name': obj.name}
185 if obj.manager:
186 result['manager'] = obj.manager.username
187 location = wkb_to_dict(obj.location)
188 result['location'] = [location['longitude'], location['latitude']]
189 result['referenceWaterLevelGaugeHeight'
190 ] = obj.reference_water_level_gauge_height
191 if obj.water:
192 result['water'] = {'label': obj.water.name, 'id': obj.water.id}
193 if obj.logs:
194 logs = []
195 for log in obj.logs:
196 logs.append(log.meta_data())
197 result['logs'] = logs
198 if obj.comment:
199 result['comment'] = obj.comment
200 return result
201
202 def to_geojson(obj):
203 location = wkb_to_dict(obj.location)
204 result = {
205 'type': 'Feature',
206 'geometry': {
207 'type': 'Point',
208 'coordinates': [location['longitude'], location['latitude']]
209 },
210 'properties': {
211 'name':
212 obj.name,
213 'referenceWaterLevelGaugeHeight':
214 obj.reference_water_level_gauge_height
215 }
216 }
217 if obj.manager:
218 result['properties']['manager'] = obj.manager.username
219 if obj.comment:
220 result['properties']['comment'] = obj.comment
221 return result
222
223
224class Device(db.Model):
225 __tablename__ = "devices"
226
227 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
228 name = db.Column(db.String(255), nullable=False)
229 owner_id = db.Column(db.Integer, db.ForeignKey('users.id'))
230 sensor_depth = db.Column(db.Float, nullable=False)
231 comment = db.Column(db.String(255))
232
233 owner = db.relationship("User", backref=db.backref("devices"), lazy=True)
234
235 def to_dict(obj):
236 result = {
237 'deviceId': obj.id,
238 'name': obj.name,
239 'sensorDepth': obj.sensor_depth
240 }
241 if obj.logs:
242 logs = []
243 for log in obj.logs:
244 logs.append(log.meta_data())
245 result['logs'] = logs
246 if obj.comment:
247 result['comment'] = obj.comment
248 return result
249
250
251class ProcessingStatus(db.Model):
252 __tablename__ = "processingstatus"
253
254 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
255 label = db.Column(db.String(255), nullable=False)
256
257 @staticmethod
258 def insert_states():
259 states = [
260 'Undefined', 'Queued for Parsing', 'Parsing',
261 'Queued for Processing', 'Processing', 'Deployed', 'To Old',
262 'Error'
263 ]
264 changed = False
265 for state in states:
266 query = ProcessingStatus.query.filter_by(label=state).all()
267 if len(query) != 1:
268 state = ProcessingStatus(label=state)
269 db.session.add(state)
270 changed = True
271 if changed:
272 db.session.commit()
273
274
275class Log(db.Model):
276 __tablename__ = "logs"
277
278 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
279 submitter_id = db.Column(db.Integer, db.ForeignKey('users.id'))
280 water_id = db.Column(db.Integer, db.ForeignKey('waters.id'))
281 device_id = db.Column(db.Integer, db.ForeignKey('devices.id'))
282 gauge_id = db.Column(db.Integer, db.ForeignKey('gauges.id'))
283 gauge_height = db.Column(db.Float, nullable=False)
284 start = db.Column(UtcDateTime, nullable=True)
285 end = db.Column(UtcDateTime, nullable=True)
286 processing_state = db.Column(
287 db.Integer, db.ForeignKey('processingstatus.id'), default=1
288 )
289 comment = db.Column(db.String(255))
290
291 submitter = db.relationship("User", backref=db.backref("logs"), lazy=True)
292 water = db.relationship("Water", backref=db.backref("logs"), lazy=True)
293 device = db.relationship("Device", backref=db.backref("logs"), lazy=True)
294 gauge = db.relationship("Gauge", backref=db.backref("logs"), lazy=True)
295 processingstatus = db.relationship(
296 "ProcessingStatus", backref=db.backref("logs"), lazy=True
297 )
298
299 def meta_data(obj):
300 result = {
301 'logId': obj.id,
302 'submitter': obj.submitter.username,
303 'water': {
304 'id': obj.water.id,
305 'label': obj.water.name,
306 },
307 'device': {
308 'id': obj.device.id,
309 'label': obj.device.name,
310 },
311 'gauge': {
312 'id': obj.gauge.id,
313 'label': obj.gauge.name,
314 },
315 'gaugeHeight': obj.gauge_height,
316 'start': '',
317 'end': '',
318 'processingState': {
319 'id': obj.processingstatus.id,
320 'label': obj.processingstatus.label
321 }
322 }
323 if obj.start is not None:
324 result['start'] = obj.start.isoformat('T')
325 if obj.end is not None:
326 result['end'] = obj.end.isoformat('T')
327
328 entries_count = 0
329 if obj.log_entries:
330 entries_count = len(obj.log_entries)
331 result['entriesCount'] = entries_count
332 if obj.comment:
333 result['comment'] = obj.comment
334 return result
335
336 def log(obj):
337 result = {'metaData': obj.meta_data()}
338 entries = []
339 if obj.log_entries:
340 for log in obj.log_entries:
341 entries.append(log.to_dict())
342 result['entries'] = entries
343 return result
344
345 def to_geojson(obj):
346 result = {'type': 'FeatureCollection', 'features': []}
347 if obj.log_entries:
348 for log in obj.log_entries:
349 location = wkb_to_dict(log.location)
350 feature = {
351 'type': 'Feature',
352 'geometry': {
353 'type':
354 'Point',
355 'coordinates': [
356 location['longitude'], location['latitude']
357 ]
358 },
359 'properties': {
360 'datetime': log.datetime.isoformat('T')
361 }
362 }
363 if log.water_depth is not None:
364 feature['properties']['waterDepth'] = log.water_depth
365 result['features'].append(feature)
366 return result
367
368
369class LogEntry(db.Model):
370 __tablename__ = "logentries"
371
372 id = db.Column(db.Integer, primary_key=True, autoincrement=True)
373 log_id = db.Column(db.Integer, db.ForeignKey('logs.id'))
374 datetime = db.Column(UtcDateTime, nullable=False)
375 # POINT(Lon Lat)
376 location = db.Column(
377 Geometry(geometry_type='POINT', srid=4326, management=True)
378 )
379 water_depth = db.Column(db.Float)
380
381 log = db.relationship("Log", backref=db.backref("log_entries"), lazy=True)
382
383 def to_dict(obj):
384 result = {'datetime': obj.datetime.isoformat('T')}
385 location = wkb_to_dict(obj.location)
386 result['location'] = [location['longitude'], location['latitude']]
387 if obj.water_depth:
388 result['waterDepth'] = obj.water_depth
389 return result
390
391
392class LogView(db.Model):
393 __table__ = create_view(
394 name='logview',
395 metadata=db.Model.metadata,
396 selectable=select([
397 Log.id, Log.submitter_id, Log.water_id, Log.device_id,
398 Log.gauge_id, Log.gauge_height, Log.start, Log.end,
399 ProcessingStatus.label,
400 func.Envelope(func.MakeLine(LogEntry.location)).label('envelope')
401 ],
402 from_obj=(
403 Log.__table__.join(
404 LogEntry, Log.id == LogEntry.log_id
405 ).join(
406 ProcessingStatus,
407 Log.processing_state == ProcessingStatus.id
408 )
409 ),
410 group_by=(Log.id)),
411 cascade_on_drop=False
412 )
413
414
415class Queue(db.Model):
416 __tablename__ = "queue"
417
418 log_id = db.Column(db.Integer, db.ForeignKey('logs.id'), primary_key=True)
419 datetime = db.Column(
420 UtcDateTime,
421 nullable=False,
422 default=datetime.datetime.now(datetime.timezone.utc)
423 )
424
425 log = db.relationship("Log", backref=db.backref("queue"), lazy=True)
426
427
428def db_setup(force=False):
429 if not database_exists(db.engine.url) or force:
430 create_database(db.engine.url)
431 if 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
432 result = db.engine.execute(
433 'SELECT count(name) FROM sqlite_master WHERE type="table" AND name="spatial_ref_sys"'
434 )
435 if result.fetchone()[0] == 1:
436 print('Spatial lite extension already loaded')
437 else:
438 print("Initiate spatial meta data for Spatialite...")
439 db.engine.execute(select([func.InitSpatialMetaData()]))
440 print("...Finished")
441 db.create_all()
442 ProcessingStatus.insert_states()
443
444
445def load_spatialite(dbapi_conn, connection_record):
446 if not 'sqlite' in flask.current_app.config['SQLALCHEMY_DATABASE_URI']:
447 return
448
449 paths = [
450 os.path.join(sys.prefix, 'lib'),
451 os.path.join(sys.prefix, 'lib64'), '/usr/lib', '/usr/lib64'
452 ]
453 for path in paths:
454 if _load_spatialite_from_path(path, dbapi_conn, connection_record):
455 return True
456 raise FileNotFoundError(
457 'mod_spatialite not found in folders {}'.format(', '.join(paths))
458 )
459
460
461def _load_spatialite_from_path(search_path, dbapi_conn, connection_record):
462 for path in Path(search_path).rglob('mod_spatialite.so*'):
463 if os.path.exists(path):
464 if flask.current_app.config['DEBUG'] and (
465 not 'TESTING' in flask.current_app.config
466 or not flask.current_app.config['TESTING']
467 ):
468 print('Enabling spatial lite extension. This may take a while')
469 # From https://geoalchemy-2.readthedocs.io/en/latest/spatialite_tutorial.html
470 dbapi_conn.enable_load_extension(True)
471 dbapi_conn.load_extension(str(path.resolve()))
472 return True
473 return False
Note: See TracBrowser for help on using the repository browser.