1
# coding utf-8
2
# classes/sweet.py
3
# class:: Sweet
4
5
from flask import current_app
6
from datetime import datetime
7
8
from swtstore.classes.database import db
9
# custom SQLAlchemy type JSONType
10
from swtstore.classes.models.types import JSONType
11
from swtstore.classes.utils import urlnorm # normalize URLs
12
from swtstore.classes.models import Context
13
from swtstore.classes.models.um import User
14
15
class Sweet(db.Model):
16
    """ customary docstring """
17
18
    __tablename__ = 'sweets'
19
20
    id = db.Column(db.Integer, primary_key=True)
21
22
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
23
    who = db.relationship('User')
24
25
    context_id = db.Column(db.Integer, db.ForeignKey('contexts.id'))
26
    what = db.relationship('Context')
27
28
    where = db.Column(db.String, nullable=False)
29
30
    how = db.Column(JSONType)
31
32
    created = db.Column(db.DateTime, default=datetime.utcnow)
33
34
35
    def __init__(self, who, what, where, how):
36
        current_app.logger.info('initing sweet..')
37
        self.who = who
38
        self.what = what
39
        self.where = urlnorm(where)
40
        self.how = how
41
42
43
    def __repr__(self):
44
        return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
45
                                                        self.what, self.where)
46
47
    def __str__(self):
48
        return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who,
49
                                                        self.what, self.where)
50
51
    # Update the sweet - only 'how' and 'where' fields can be updated
52
    def update(self, **kwargs):
53
        if kwargs.get('how'):
54
            self.how = kwargs.get('how')
55
            self.persist()
56
        if kwargs.get('where'):
57
            self.where = kwargs.get('where')
58
            self.persist()
59
60
        return None
61
62
63
    # create multiple sweets from a list of JSON
64
    @staticmethod
65
    def createSweets(who, payload):
66
        # the payload has to be a list; a list of swts
67
        for each in payload:
68
            if 'what' not in each and 'where' not in\
69
                each and 'how' not in each:
70
71
                raise InvalidPayload('Invalid payload %s \n for creating\
72
                                     mutiple sweets' % (each))
73
                return None
74
75
        # all ok. create swts from the list now
76
        swts = []
77
        for each in payload:
78
79
            what = Context.getByName(each['what'])
80
81
            if what is None:
82
                current_app.logger.info('Context "%s" do not exist. Aborting',
83
                                    what)
84
                g.error = 'Context do not exist'
85
                abort(400) # this context doesn't exist!
86
87
            current_app.logger.debug('SWEET PAYLOAD\n---\n%s\n%s\n%s\n%s\n----',
88
                                 who, what, each['where'], each['how'])
89
90
            new_sweet = Sweet(who, what, each['where'], each['how'])
91
92
            new_sweet.persist()
93
            current_app.logger.debug('New Sweet %s', new_sweet)
94
            swts.append(new_sweet)
95
96
        return swts
97
98
    # get Sweets for frontend
99
    @staticmethod
100
    def getFrontendSwts():
101
        return Sweet.query.order_by(Sweet.created.desc()).all()
102
103
    # get sweets all sweets authored by a particular user
104
    @staticmethod
105
    def getByCreator(user):
106
        return Sweet.query.filter_by(who=user).\
107
                order_by(Sweet.created.desc()).all()
108
109
    # allow to query all sweets based on "who", "what" and "where" params
110
    @staticmethod
111
    def queryByAll(params):
112
        if params.get('who'):
113
            params['who'] = User.getByName(params['who'])
114
        if params.get('what'):
115
            params['what'] = Context.getByName(params['what'])
116
117
        return Sweet.query.filter_by(**params).all()
118
119
    # return a dictionary of data members
120
    def to_dict(self):
121
        return {
122
            'id': self.id,
123
            'who': self.who.username,
124
            'user_id': self.user_id,
125
            'what': self.what.name,
126
            'context_id': self.context_id,
127
            'where': self.where,
128
            'how': self.how,
129
            'created': self.created.isoformat()
130
        }
131
132
133
    # create and persist the sweet to the database
134
    def persist(self):
135
136
        current_app.logger.debug('Commiting sweet %s to db', self)
137
        db.session.add(self)
138
        db.session.commit()