cygnal/server/models.py

60 lines
1.3 KiB
Python
Raw Permalink Normal View History

2018-06-25 17:12:17 +02:00
#!/usr/bin/env python
# coding: utf-8
"""
Models and database definition
"""
2018-06-27 15:48:17 +02:00
import os
2018-06-25 17:12:17 +02:00
import arrow
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-06-27 15:48:17 +02:00
db = connect(os.environ.get('DATABASE', 'sqlite:///reports.db'))
2018-06-25 17:12:17 +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()
datetime = peewee.DateTimeField(
default=lambda: arrow.utcnow().replace(microsecond=0).naive
2018-06-25 17:12:17 +02:00
)
expiration_datetime = peewee.DateTimeField(null=True)
2018-06-25 17:12:17 +02:00
is_open = peewee.BooleanField(default=True)
upvotes = peewee.IntegerField(default=0)
downvotes = peewee.IntegerField(default=0)
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"
}
}