source: src/mapservice/server_impl/database/Model.py@ 77cd9cf

debian/bullseye
Last change on this file since 77cd9cf was 8818b65, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago

Removed sqlalchemy_utc as dependency

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