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, User |
13 |
from swtstore.classes.exceptions import InvalidPayload, ContextDoNotExist |
14 |
|
15 |
|
16 |
class Sweet(db.Model): |
17 |
""" customary docstring """ |
18 |
|
19 |
__tablename__ = 'sweets' |
20 |
|
21 |
id = db.Column(db.Integer, primary_key=True) |
22 |
|
23 |
user_id = db.Column(db.Integer, db.ForeignKey('users.id')) |
24 |
who = db.relationship('User') |
25 |
|
26 |
context_id = db.Column(db.Integer, db.ForeignKey('contexts.id')) |
27 |
what = db.relationship('Context') |
28 |
|
29 |
where = db.Column(db.UnicodeText, nullable=False) |
30 |
|
31 |
how = db.Column(JSONType) |
32 |
|
33 |
created = db.Column(db.DateTime, default=datetime.utcnow) |
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 |
def __repr__(self): |
43 |
return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who, |
44 |
self.what, self.where) |
45 |
|
46 |
def __str__(self): |
47 |
return '[Sweet Object: <%s : @%s: #%s : %s>]' % (self.id, self.who, |
48 |
self.what, self.where) |
49 |
|
50 |
# Update the sweet - only 'how' and 'where' fields can be updated |
51 |
def update(self, **kwargs): |
52 |
if kwargs.get('how'): |
53 |
self.how = kwargs.get('how') |
54 |
self.persist() |
55 |
if kwargs.get('where'): |
56 |
self.where = kwargs.get('where') |
57 |
self.persist() |
58 |
|
59 |
return None |
60 |
|
61 |
# create multiple sweets from a list of JSON |
62 |
@staticmethod |
63 |
def createSweets(who, payload): |
64 |
# the payload has to be a list; a list of swts |
65 |
for each in payload: |
66 |
if 'what' not in each and 'where' not in each and 'how' not in\ |
67 |
each: |
68 |
|
69 |
raise InvalidPayload('Invalid payload %s \n while creating\ |
70 |
mutiple sweets' % (each)) |
71 |
return None |
72 |
|
73 |
# all ok. create swts from the list now |
74 |
swts = [] |
75 |
for each in payload: |
76 |
|
77 |
what = Context.getByName(each['what']) |
78 |
|
79 |
if what is None: |
80 |
raise ContextDoNotExist('Context %s do not exist!' % |
81 |
(each['what'])) |
82 |
|
83 |
current_app.logger.debug('SWEET PAYLOAD\n---\n%s\n%s\n%s\n%s\n----', |
84 |
who, what, each['where'], each['how']) |
85 |
|
86 |
new_sweet = Sweet(who, what, each['where'], each['how']) |
87 |
|
88 |
new_sweet.persist() |
89 |
current_app.logger.debug('New Sweet %s', new_sweet) |
90 |
swts.append(new_sweet) |
91 |
|
92 |
return swts |
93 |
|
94 |
# get Sweets for frontend |
95 |
@staticmethod |
96 |
def getFrontendSwts(): |
97 |
return Sweet.query.order_by(Sweet.created.desc()).all() |
98 |
|
99 |
# get all sweets authored by a particular user |
100 |
@staticmethod |
101 |
def getByCreator(user): |
102 |
return Sweet.query.filter_by(who=user).\ |
103 |
order_by(Sweet.created.desc()).all() |
104 |
|
105 |
# allow to query all sweets based on "who", "what" and "where" params |
106 |
@staticmethod |
107 |
def queryByAll(params): |
108 |
if params.get('who'): |
109 |
params['who'] = User.getByName(params['who']) |
110 |
if params.get('what'): |
111 |
params['what'] = Context.getByName(params['what']) |
112 |
|
113 |
return Sweet.query.filter_by(**params).all() |
114 |
|
115 |
# return a dictionary of data members |
116 |
def to_dict(self): |
117 |
return { |
118 |
'id': self.id, |
119 |
'who': self.who.username, |
120 |
'user_id': self.user_id, |
121 |
'what': self.what.name, |
122 |
'context_id': self.context_id, |
123 |
'where': self.where, |
124 |
'how': self.how, |
125 |
#'created': self.created.isoformat() |
126 |
'created': self.created.strftime('%a, %d %b %Y, %I:%M %p UTC'), |
127 |
} |
128 |
|
129 |
# create and persist the sweet to the database |
130 |
def persist(self): |
131 |
|
132 |
current_app.logger.debug('Commiting sweet %s to db', self) |
133 |
db.session.add(self) |
134 |
db.session.commit() |