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