2018-06-25 17:12:17 +02:00
|
|
|
#!/usr/bin/env python
|
|
|
|
# coding: utf-8
|
|
|
|
"""
|
|
|
|
Models and database definition
|
|
|
|
"""
|
2019-05-08 19:37:52 +02:00
|
|
|
import json
|
2018-06-27 15:48:17 +02:00
|
|
|
import os
|
|
|
|
|
2018-06-27 22:11:30 +02:00
|
|
|
import bottle
|
2018-06-25 17:12:17 +02:00
|
|
|
import peewee
|
2018-06-27 15:48:17 +02:00
|
|
|
from playhouse.db_url import connect
|
2018-06-25 17:12:17 +02:00
|
|
|
from playhouse.shortcuts import model_to_dict
|
|
|
|
|
2018-09-12 13:51:53 +02:00
|
|
|
from server.tools import UTC_now
|
|
|
|
|
2018-06-27 15:48:17 +02:00
|
|
|
db = connect(os.environ.get('DATABASE', 'sqlite:///reports.db'))
|
2018-06-25 17:12:17 +02:00
|
|
|
|
|
|
|
|
2018-06-27 22:11:30 +02:00
|
|
|
@bottle.hook('before_request')
|
|
|
|
def _connect_db():
|
|
|
|
db.connect()
|
|
|
|
|
|
|
|
|
|
|
|
@bottle.hook('after_request')
|
|
|
|
def _close_db():
|
|
|
|
if not db.is_closed():
|
|
|
|
db.close()
|
|
|
|
|
|
|
|
|
2018-06-25 17:12:17 +02:00
|
|
|
class BaseModel(peewee.Model):
|
|
|
|
"""
|
|
|
|
Common base class for all models
|
|
|
|
"""
|
|
|
|
class Meta:
|
|
|
|
database = db
|
|
|
|
|
|
|
|
|
|
|
|
class Report(BaseModel):
|
|
|
|
"""
|
|
|
|
A report object
|
|
|
|
"""
|
|
|
|
type = peewee.CharField(max_length=255)
|
|
|
|
lat = peewee.DoubleField()
|
|
|
|
lng = peewee.DoubleField()
|
2018-09-12 13:51:53 +02:00
|
|
|
first_report_datetime = peewee.DateTimeField(
|
|
|
|
default=UTC_now
|
|
|
|
)
|
2018-06-25 17:12:17 +02:00
|
|
|
datetime = peewee.DateTimeField(
|
2018-09-12 13:51:53 +02:00
|
|
|
default=UTC_now
|
2018-06-25 17:12:17 +02:00
|
|
|
)
|
2018-07-10 15:55:45 +02:00
|
|
|
expiration_datetime = peewee.DateTimeField(null=True)
|
2018-07-05 22:40:24 +02:00
|
|
|
upvotes = peewee.IntegerField(default=0)
|
|
|
|
downvotes = peewee.IntegerField(default=0)
|
2018-11-29 11:07:22 +01:00
|
|
|
source = peewee.CharField(max_length=255, default='')
|
2018-10-30 16:58:57 +01:00
|
|
|
shape_geojson = peewee.TextField(default=None, null=True)
|
2018-06-25 17:12:17 +02:00
|
|
|
|
|
|
|
def to_json(self):
|
|
|
|
return {
|
|
|
|
"type": "reports",
|
|
|
|
"id": self.id,
|
|
|
|
"attributes": {
|
|
|
|
k: v for k, v in model_to_dict(self).items()
|
|
|
|
if k != "id"
|
|
|
|
}
|
2018-06-26 11:39:43 +02:00
|
|
|
}
|
2019-05-08 19:37:52 +02:00
|
|
|
|
|
|
|
def to_geojson_feature(self):
|
|
|
|
properties = {
|
|
|
|
"type": "reports",
|
|
|
|
}
|
|
|
|
for k, v in model_to_dict(self).items():
|
|
|
|
properties[k] = v
|
|
|
|
|
|
|
|
geometry = None
|
|
|
|
if self.shape_geojson:
|
|
|
|
geometry = json.loads(self.shape_geojson)
|
|
|
|
else:
|
|
|
|
geometry = {
|
|
|
|
"type": "Point",
|
|
|
|
"coordinates": [self.lng, self.lat]
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
"type": "Feature",
|
|
|
|
"properties": properties,
|
|
|
|
"geometry": geometry,
|
|
|
|
}
|