1
# coding utf-8
2
# classes/sweet.py
3
# class:: Sweet
4
5
from datetime import datetime
6
7
from swtstore.classes.database import db
8
# custom SQLAlchemy type JSONType
9
from swtstore.classes.models.types import JSONType
10
from swtstore.classes.utils import urlnorm # normalize URLs
11
12
class Sweet(db.Model):
13
    """ customary docstring """
14
15
    __tablename__ = 'sweets'
16
17
    id = db.Column(db.Integer, primary_key=True)
18
19
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
20
    who = db.relationship('User')
21
22
    context_id = db.Column(db.Integer, db.ForeignKey('contexts.id'))
23
    what = db.relationship('Context')
24
25
    where = db.Column(db.String, nullable=False)
26
27
    how = db.Column(JSONType)
28
29
    created = db.Column(db.DateTime, default=datetime.utcnow)
30
31
32
    def __init__(self, who, what, where, how):
33
        print 'initing sweet..'
34
        self.who = who
35
        self.what = what
36
        self.where = urlnorm(where)
37
        self.how = how
38
39
40
    def __repr__(self):
41
        return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
42
                                                        self.what, self.where)
43
44
    def __str__(self):
45
        return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
46
                                                        self.what, self.where)
47
48
    # return a dictionary of data members
49
    def to_dict(self):
50
        print self.created
51
        return {
52
            'id': self.id,
53
            'who': self.who,
54
            'what': self.what.name,
55
            'context_id': self.context_id,
56
            'where': self.where,
57
            'how': self.how,
58
            'created': self.created.isoformat()
59
        }
60
61
62
    # create and persist the sweet to the database
63
    def persist(self):
64
65
        db.session.add(self)
66
        db.session.commit()