forked from arthu9/BookshelfV2-API
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
392 lines (296 loc) · 14 KB
/
app.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
from flask import Flask, jsonify, request, make_response, render_template
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import jwt
import datetime
from functools import wraps
from flask_httpauth import HTTPBasicAuth
from models import *
from sqlalchemy import cast
def token_required(f):
@wraps(f)
def decorated(*args, **kwargs):
token = None
if 'x-access-token' in request.headers:
token = request.headers['x-access-token']
if not token:
return jsonify({'message' : 'Token is missing!'}), 401
try:
data = jwt.decode(token, app.config['SECRET_KEY'])
current = User.query.filter_by(id=data['id']).first()
current_user = current.id
except:
return jsonify({'message': 'Token is invalid!'}), 401
return f(current_user, *args, **kwargs)
return decorated
@app.route('/users', methods=['GET'])
@token_required
def get_all_users(current_user):
users = User.query.all()
output = []
for user in users:
user_data = {}
user_data['id'] = user.id
user_data['username'] = user.username
user_data['password'] = user.password
user_data['first_name'] = user.first_name
user_data['last_name'] = user.last_name
user_data['contact_number'] = user.contact_number
user_data['birth_date'] = user.birth_date
user_data['gender'] = user.gender
user_data['longitude'] = user.longitude
user_data['latitude'] = user.latitude
user_data['profpic'] = user.profpic
output.append(user_data)
return jsonify({'users': output})
@app.route('/user/info', methods=['GET'])
@token_required
def get_one_user(current_user):
user = User.query.filter_by(id=current_user).first()
if not user:
return jsonify({'message':'No user found!'})
user_data = {}
user_data['id'] = user.id
user_data['username'] = user.username
user_data['password'] = user.password
user_data['first_name'] = user.first_name
user_data['last_name'] = user.last_name
user_data['contact_number'] = user.contact_number
user_data['birth_date'] = user.birth_date
user_data['gender'] = user.gender
user_data['longitude'] = user.longitude
user_data['latitude'] = user.latitude
user_data['profpic'] = user.profpic
return jsonify({'information': user_data})
@app.route('/signup', methods=['POST'])
def create_user():
data = request.get_json()
hashed_password = generate_password_hash(data['password'], method='sha256')
new_user = User(username=data['username'], password=hashed_password, first_name=data['first_name'],last_name=data['last_name'],contact_number=data['contact_number'], birth_date=data['birth_date'], gender = data['gender'], longitude=data['longitude'], latitude=data['latitude'])
user = User.query.filter_by(username=data['username']).first()
if user is None:
db.session.add(new_user)
db.session.commit()
return jsonify({'message': 'New user created!'})
else:
return jsonify({'message': 'Username already created'})
@app.route('/login', methods=['GET', 'POST'])
def login():
auth = request.authorization
if not auth or not auth.username or not auth.password:
return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})
user = User.query.filter_by(username=auth.username).first()
if not user:
return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})
if check_password_hash(user.password, auth.password):
token = jwt.encode({'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)}, app.config['SECRET_KEY'])
return jsonify({'token': token.decode('UTF-8')})
return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm="Login required!"'})
@app.route('/search', methods=['GET', 'POST'])
def search():
data = request.get_json()
item = '%' + data['item'] + '%'
books = Books.query.filter(((Books.title.like(item)) | (Books.year_published.like(item)) | (Books.types.like(item)) | cast(Books.edition, sqlalchemy.String).like(str(item)) | (Books.isbn.like(item)))).all()
if books is None:
return jsonify({'message':'No book found!'})
output = []
for book in books:
user_data = {}
user_data['title'] = book.title
user_data['description'] = book.description
user_data['year_published'] = book.year_published
user_data['isbn'] = book.isbn
user_data['types'] = book.types
user_data['publisher_id'] = book.publisher_id
output.append(user_data)
return jsonify({'book': output})
@app.route('/user/bookshelf/search', methods=['GET','POST'])
@token_required
def searchbookshelf(current_user):
data = request.get_json()
item = '%'+data['item']+'%'
books = Bookshelf.query.filter_by(bookshef_owner = current_user).first()
shelf_id = books.bookshelf_id
books = ContainsAsscociation.query.join(Books).filter((cast(shelf_id, sqlalchemy.String).like(item)) & ((Books.title.like(item)) | (
Books.year_published.like(item)) | (Books.types.like(item)) | cast(Books.edition, sqlalchemy.String).like(item) | (Books.isbn.like(item)))).all()
if books is None:
return jsonify({'message':'No book found!'})
output = []
for book in books:
user_data = {}
user_data['title'] = book.title
user_data['description'] = book.description
user_data['year_published'] = book.year_published
user_data['isbn'] = book.isbn
user_data['types'] = book.types
user_data['publisher_id'] = book.publisher_id
output.append(user_data)
return jsonify({'book': output})
@app.route('/user/bookshelf', methods=['GET'])
@token_required
def viewbook(current_user):
books = Bookshelf.query.filter_by(bookshef_owner = current_user).first()
shelf_id = books.bookshelf_id
contains = ContainsAsscociation.query.filter_by(shelf_id = shelf_id).first()
shelf_id = contains.shelf_id
Book = Books.query.join(ContainsAsscociation).filter_by(shelf_id = shelf_id).all()
# q = (db.session.query(Books, Bookshelf, ContainsAsscociation, Author)
# .filter(Bookshelf.bookshef_owner == id)
# .filter(ContainsAsscociation.shelf_id == Bookshelf.bookshelf_id)
# .filter(Books.book_id == ContainsAsscociation.book_id)
# .filter(Author.author_id == Books.publisher_id)
# .all())
output = []
for book in Book:
user_data = {}
user_data['title'] = book.title
user_data['description'] = book.description
user_data['edition'] = book.edition
user_data['year'] = book.year_published
user_data['isbn'] = book.isbn
user_data['types'] = book.types
user_data['publisher_id'] = book.publisher_id
output.append(user_data)
return jsonify({'book': output})
@app.route('/user/addbook', methods=['POST'])
@token_required
def addbook(current_user):
data = request.get_json()
book = Books.query.filter((Books.title == data['title']) & (Books.edition == data['edition']) & (Books.year_published == data['year']) & (Books.isbn == data['isbn'])).first()
publisher = Publisher.query.filter(Publisher.publisher_name == data['publisher_name']).first()
author = Author.query.filter(
(Author.author_first_name == data['author_fname']) & (Author.author_last_name == data['author_lname'])).first()
if (book is None) or (publisher is None) or (author is None):
if publisher is None:
newPublisher = Publisher(publisher_name= data['publisher_name'])
db.session.add(newPublisher)
db.session.commit()
publisher_id = Publisher.query.filter((Publisher.publisher_name == data['publisher_name'])).first()
if author is None:
author = Author(data['author_fname'], data['author_lname'])
db.session.add(author)
db.session.commit()
elif author is not None:
auth_id = Author.query.filter((Author.author_first_name == data['author_fname']) and (Author.author_last_name == data['author_lname'])).first()
elif publisher is not None:
publisher_id = Publisher.query.filter((Publisher.publisher_name == data['publisher_name'])).first()
if author is None:
authbook = Author(data['author_fname'], data['author_lname'])
db.session.add(authbook)
db.session.commit()
elif author is not None:
auth_id = Author.query.filter((Author.author_first_name == data['author_fname']) and (
Author.author_last_name == data['author_lname'])).first()
publisher = Publisher.query.filter(Publisher.publisher_name == data['publisher_name']).first()
publisher_id = publisher.publisher_id
book = Books(title = data['title'],edition = data['edition'], year_published = data['year'], isbn =data['isbn'], types =data['types'], publisher_id= publisher_id)
db.session.add(book)
db.session.commit()
written = WrittenByAssociation(auth_id.author_id, book.book_id)
db.session.add(written)
db.session.commit()
bookshelf = Bookshelf.query.filter_by(bookshef_owner=current_user).first()
shelf_id = bookshelf.bookshelf_id
contain = ContainsAsscociation(shelf_id, book.book_id, 1, 'YES')
db.session.add(contain)
db.session.commit()
return jsonify({'message': 'New book created!'})
else:
bookshelf = Bookshelf.query.filter_by(bookshef_owner=current_user).first()
shelf_id = bookshelf.bookshelf_id
bookquantity = ContainsAsscociation.query.filter((ContainsAsscociation.shelf_id == shelf_id) & (ContainsAsscociation.book_id == book.book_id)).first()
if bookquantity is None:
contain = ContainsAsscociation(shelf_id, book.book_id, 1, 'YES')
db.session.add(contain)
db.session.commit()
else:
curQuant = bookquantity.quantity
bookquantity.quantity = int(curQuant + 1)
db.session.commit()
return jsonify({'message': 'New book counted!'})
# {"title": "new book","edition": "20", "year": "2018", "isbn": "SEVENTEEN", "types": "HARD" , "publisher_name":"DK", "author_fname": "SEANNE", "author_lname": "CANOY"}
@app.route('/user/bookshelf/availability', methods=['GET'])
@token_required
def viewbooks(current_user):
books = ContainsAsscociation.query.join(Bookshelf).filter_by(bookshef_owner = current_user).all()
if books == []:
return jsonify({'message': 'No book found!'})
else:
output = []
for book in books:
user_data = {}
user_data['shelf_id'] = book.shelf_id
user_data['book_id'] = book.book_id
user_data['quantity'] = book.quantity
user_data['availability'] = book.availability
output.append(user_data)
return jsonify({'book': output})
@app.route('/')
def category():
return 0
# #COMMENT (USER)
# # @app.route('/profile/commentUser/', methods=['GET', 'POST'])
# @app.route('/profile/commentUser/<int:user_id>', methods=['GET', 'POST'])
# def comment(user_id):
#
# if user_id == current_user.id:
# comments = UserCommentAssociation.query.filter((UserCommentAssociation.user_idCommentee == current_user.id))
# x = []
# for c in comments:
# s = User.query.filter_by(id=c.user_idCommenter).first()
# x.append(s.first_name + ' ' + s.last_name)
# return jsonify({'message': 'ok', 'comments': comments, 'name': x,'currrent_user': current_user})
# else:
# user = User.query.filter_by(id=user_id).first()
# otheruserId = user_id
# comments = UserCommentAssociation.query.filter((UserCommentAssociation.user_idCommentee == user_id))
# xs = []
# for c in comments:
# s = User.query.filter_by(id=c.user_idCommenter).first()
# xs.append(s.first_name + ' ' + s.last_name)
# if request.method == 'POST':
# comment = request.form['comment']
# commentOld = UserCommentAssociation.query.filter((UserCommentAssociation.user_idCommentee == otheruserId) & (
# UserCommentAssociation.user_idCommenterter == current_user.id)).first()
#
# if commentOld is not None:
# commentOld.comment = comment
# db.session.commit()
#
# else:
# newCommenter = UserCommentAssociation(current_user.id, otheruserId,comment)
# db.session.add(newCommenter)
# db.session.commit()
# return jsonify({'message': 'ok', 'user_id': user_id})
# return jsonify({'message': 'ok', 'user': user, 'comments': comments, 'name': xs, 'currrent_user': current_user})
#
#COMMENT (BOOK)
# @app.route('/commentBook/', methods=['POST', 'GET'])
@app.route('/commentBook/<int:book_id>', methods=['POST'])
def commentbook(book_id):
data = request.get_json()
newComment = BookCommentAssociation(comment=data['comment'])
bcomment = BookCommentAssociation.query.filter(BookCommentAssociation.book_id == book_id).first()
if bcomment is not None:
db.session.add(newComment)
db.session.commit()
return jsonify({'message': 'comment posted!'})
else:
return jsonify({'message': 'cant post comment :(', 'book_id': book_id})
# @app.route('/ratings/<int:book_id>', methods=['POST'])
# def ratings(book_id):
#
# data = request.get_json()
#
# current_user = User.query.filter_by(id=id).first()
#
# rate = BookRateAssociation(rating=data['rating'])
#
# rateOld = BookRateAssociation.query.filter(
# (BookRateAssociation.user_id == current_user.id) & (BookRateAssociation.book_id == book_id)).first()
#
# if rateOld is None:
# rateOld.rating = rate
# db.session.commit()
if __name__ == '__main__':
app.run (debug=True)