-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
358 lines (308 loc) · 12.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import pymongo
from flask import jsonify
from pymongo.server_api import ServerApi
from config import Config
from bson.objectid import ObjectId
from errors.not_found import NotFound
from errors.validation_error import ValidationError
from validators.validation_publications import validate_patch_publication, validate_delete_publication
client = pymongo.MongoClient(
Config.CONNECTION_STRING,
server_api=ServerApi('1'))
db = client.noSql_database
class User:
def __init__(self, username, password=None, role='user', _id=None):
self.username = username
self.password = password
self.role = role
if _id is not None:
_id = str(_id)
self._id = _id
def get_id(self):
return self._id
def create(self):
# Katsotaan onko sen niminen käyttäjä jo olemassa
user = db.users.find_one({'username': self.username})
if user is not None:
raise ValidationError(message='username must be unique')
# Jos käyttäjää ei ollut olemassa niin luodaan se
result = db.users.insert_one({'username': self.username, 'role': self.role, 'password': self.password})
self._id = str(result.inserted_id)
def update(self):
_filter = {'_id': ObjectId(self._id)}
_update = {
'$set': {'username': self.username}
}
# hae käyttäjä jonka käyttäjänimi on self.usernamen arvo ja _id eri suuri kuin self._id:n arvo
user = db.users.find_one({'username': self.username, '_id': {'$ne': ObjectId(self._id)}})
if user is not None:
raise ValidationError(message="username must be unique")
db.users.update_one(_filter, _update)
def update_password(self):
_filter = {'_id': ObjectId(self._id)}
_update = {
'$set': {'password': self.password}
}
db.users.update_one(_filter, _update)
def to_json(self):
return {
'_id': str(self._id),
'username': self.username,
'role': self.role
}
# Palauttaa listan jsoneita. Jokainen User objekti listassa muutettu json muotoon.
@staticmethod
def list_to_json(users_list):
users = []
for user in users_list:
users.append(user.to_json())
return users
@staticmethod
def get_all():
users_cursor = db.users.find()
users_list = list(users_cursor)
users = []
for user_dictionary in users_list:
users.append(User(user_dictionary['username'], role=user_dictionary['role'], _id=user_dictionary['_id']))
return users
@staticmethod
def get_by_id(_id):
user_dictionary = db.users.find_one({'_id': ObjectId(_id)})
if user_dictionary is None:
raise NotFound(message="user not found")
user = User(user_dictionary['username'], role=user_dictionary['role'], _id=user_dictionary['_id'])
return user
@staticmethod
def get_by_username(username):
user_dictionary = db.users.find_one({'username': username})
if user_dictionary is None:
raise NotFound(message="user not found")
user = User(user_dictionary['username'], role=user_dictionary['role'], _id=user_dictionary['_id'],
password= user_dictionary['password'])
return user
@staticmethod
def delete_by_id(_id):
db.users.delete_one({'_id': ObjectId(_id)})
class Publication:
def __init__(self,
title,
description,
url,
owner=None, # Oletusarvot owner=None, visibility=2, likes=[], _id=None, share_link=None, shares
visibility=2,
likes=None, # likes lista sisältää käyttäjien _id arvoja ObjectId
share_link=None,
shares=0,
_id=None):
if likes is None:
likes = []
self.likes = likes
self.title = title
self.description = description
self.url = url
self.owner = owner
self.visibility = visibility
self.likes = likes
self.share_link = share_link
self.shares = shares
if _id is not None:
_id = str(_id)
self._id = _id
# CRUD:n C (Create)
def create(self):
result = db.publications.insert_one({
'title': self.title,
'description': self.description,
'url': self.url,
'owner': ObjectId(self.owner),
'visibility': self.visibility
})
self._id = str(result.inserted_id)
def update(self):
_filter = {'_id': ObjectId(self._id)}
_update = {
'$set': {'title': self.title, 'description': self.description, 'visibility': self.visibility}
}
print("päivitetään näillä arvoilla:")
print(_update)
db.publications.update_one(_filter, _update)
def like(self):
_filter = {'_id': ObjectId(self._id)}
_update = {
'$set': {'likes': self.likes}
}
db.publications.update_one(_filter, _update)
def share(self):
_filter = {'_id': ObjectId(self._id)}
_update = {
'$set': {'shares': self.shares, 'share_link': self.share_link}
}
db.publications.update_one(_filter, _update)
# Palauttaa Jsonin objektista
def to_json(self):
likes = []
for user_id in self.likes:
likes.append(str(user_id))
owner = self.owner
if owner is not None:
owner = str(owner)
return {
'_id': str(self._id),
'title': self.title,
'description': self.description,
'url': self.url,
'owner': owner,
'visibility': self.visibility,
'likes': likes, # 'likes': [str(user_id) for user_id in self.likes]
'shares': self.shares,
'share_link': self.share_link
}
# Palauttaa listan Jsoneita. Jokainen Publication objekti listassa muutettu json muotoon.
@staticmethod
def list_to_json(publication_list):
publications = []
for publication in publication_list:
publications.append(publication.to_json())
return publications
# Palauttaa Publication objektin
@staticmethod
def _from_json(publication):
publication_object = Publication(publication['title'], publication['description'], publication['url'],
# toinen argumentti on oletusarvo ensimmäiselle argumentille,
# jos ensimmäistä argumenttia ei löydy
_id=publication['_id'], owner=publication.get('owner', None),
visibility=publication.get('visibility', 2),
likes=publication.get('likes', []),
share_link=publication.get('share_link', None),
shares=publication.get('shares', 0))
return publication_object
# Palauttaa listan Publication objekteja
@staticmethod
def _list_from_json(list_of_dictionaries):
publications = []
for publication in list_of_dictionaries:
publication_object = Publication._from_json(publication)
publications.append(publication_object)
return publications
@staticmethod
def get_all():
publications_cursor = db.publications.find()
publications_list = list(publications_cursor)
publications = Publication._list_from_json(publications_list)
return publications
@staticmethod
def get_by_id(_id):
publication_dictionary = db.publications.find_one({'_id': ObjectId(_id)})
if publication_dictionary is None:
raise NotFound(message="publication not found")
publication = Publication._from_json(publication_dictionary)
return publication
# palauttaa vain kaikille julkiset publicationit
@staticmethod
def get_by_visibility(visibility=2):
publications_cursor = db.publications.find({'visibility': visibility})
publications_list = list(publications_cursor)
publications = Publication._list_from_json(publications_list)
return publications
# return type changed from cursor to doc
@staticmethod
def get_one_by_id_and_visibility(_id, visibility=2):
publication = db.publications.find({'_id': ObjectId(_id), 'visibility': visibility})
publication_doc = publication.next()
if publication is None:
raise NotFound(message="publication not found")
return Publication._from_json(publication_doc)
@staticmethod
def get_logged_in_users_and_public_publications(logged_in_user):
_filter = {
'$or': [
# etsitään käyttäjän omat julkaisut
{'owner': ObjectId(logged_in_user['sub'])},
# etsitään julkaisut joilla visibility 1 tai 2
{'visibility': {'$in': [1, 2]}}
]
}
publications_cursor = db.publications.find(_filter)
publications_list = list(publications_cursor)
publications = Publication._list_from_json(publications_list)
return publications
@staticmethod
def get_logged_in_users_and_public_publication(_id, logged_in_user):
""" SELECT * FROM publications WHERE id = ? AND (owner = ? OR visibility IN (1, 2)) LIMIT 1; """
_filter = {
# hae ensimmäinen, jossa _id = _id ja (owner = sisäänkirjautunut käyttäjä tai visibility 1 tai visibility 2)
'_id': ObjectId(_id),
'$or': [
{'owner': ObjectId(logged_in_user['sub'])},
{'visibility': {'$in': [1, 2]}}
]
}
publication = db.publications.find_one(_filter)
if publication is None:
raise NotFound(message="publication not found")
publication_object = Publication._from_json(publication)
return publication_object
@staticmethod
def delete_by_id(_id):
result = db.publications.delete_one({'_id': ObjectId(_id)})
if result.deleted_count == 0:
raise NotFound(message="publication not found")
@staticmethod
def delete_by_id_and_owner(_id, owner):
result = db.publications.delete_one({'_id': ObjectId(_id), 'owner': ObjectId(owner['sub'])})
if result.deleted_count == 0:
raise NotFound(message="publication not found")
# admin saa muokata kenen tahansa julkaisua.
@staticmethod
@validate_patch_publication
def admin_patch(publication):
publication.update()
return jsonify(publication=publication.to_json())
# admin saa poistaa kenen tahansa julkaisua.
@staticmethod
@validate_delete_publication
def admin_delete(_id):
db.publications.delete_one({'_id': ObjectId(_id)})
return ""
class Comment:
def __init__(self, body, owner, publication, _id=None):
self.body = body
self.owner = str(owner)
self.publication = str(publication)
if _id is not None:
_id = str(_id)
self._id = _id
def to_json(self):
return {
'_id': str(self._id),
'body': self.body,
'owner': str(self.owner),
'publication': str(self.publication)
}
@staticmethod
def list_to_json(comments):
comments_in_json = []
for comment in comments:
comments_in_json.append(comment.to_json())
return comments_in_json
def create(self):
result = db.comments.insert_one({'body': self.body, 'owner': ObjectId(self.owner),
'publication': ObjectId(self.publication)})
self._id = str(result.inserted_id)
@staticmethod
def get_all_by_publication(_publication_id):
comments = []
comments_cursor = db.comments.find({'publication': ObjectId(_publication_id)})
for comment in comments_cursor:
comments.append(Comment(comment['body'], comment['owner'], comment['publication'], _id=comment['_id']))
return comments
@staticmethod
def update_by_id(_comment_id, body):
_filter = {'_id': ObjectId(_comment_id)}
_update = {'$set': {'body': body}}
db.comments.update_one(_filter, _update)
comment = db.comments.find_one({'_id': ObjectId(_comment_id)})
return Comment(body, comment['owner'], comment['publication'], _id=comment['_id'])
@staticmethod
def delete_by_id(_comment_id):
db.comments.delete_one({'_id': ObjectId(_comment_id)})