/
views.py
779 lines (722 loc) · 31 KB
/
views.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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
#!/usr/bin/env Python
import json
import random
import string
from flask import (Flask, render_template, request, redirect, jsonify,
url_for, flash, make_response)
from flask import session as login_session
from sqlalchemy import create_engine, asc, text
from sqlalchemy.orm import sessionmaker, joinedload, relationship
import requests
from models import (Base, User, Items, Categories, Inventory, ItemCategories,
ItemTags, ItemPhotos)
import datetime
# IMPORTS FOR THIS STEP
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
import httplib2
import logging
# DEBUGGING - Turn on logging to text file.
""" REMOVE LOG FILE FROM GIT ADD ."""
logging.basicConfig(level=logging.DEBUG, filename="PythonLogs_Catalog.txt")
# logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
app = Flask(__name__)
# DEBUGGING - Echo the SQL
# app.config['SQLALCHEMY_ECHO'] = True
CLIENT_ID = json.loads(open('client_secrets.json',
'r').read())['web']['client_id']
APPLICATION_NAME = "HomeBuilt! Catalog Application"
# Connect to Database and create database session
engine = create_engine('sqlite:///catalog.db',
connect_args={'check_same_thread': False})
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# Set a current data parameter for future use in database records updates
currentDateTime = datetime.datetime.now()
# print(currentDateTime)
# Create anti-forgery state token
@app.route('/login')
def showLogin():
state = ''.join(random.choice(string.ascii_uppercase +
string.digits) for x in xrange(32))
login_session['state'] = state
# return "The current session state is %s" % login_session['state']
return render_template('login.html', STATE=state)
@app.route('/gconnect', methods=['POST'])
def gconnect():
# Validate state token
if request.args.get('state') != login_session['state']:
response = make_response(json.dumps('Invalid state parameter.'), 401)
response.headers['Content-Type'] = 'application/json'
return render_template('error.html', error=response)
# Obtain authorization code
code = request.data
try:
# Upgrade the authorization code into a credentials object
oauth_flow = flow_from_clientsecrets('client_secrets.json', scope='')
oauth_flow.redirect_uri = 'postmessage'
credentials = oauth_flow.step2_exchange(code)
except FlowExchangeError:
response = make_response(
json.dumps('Failed to upgrade the authorization code.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Check that the access token is valid.
access_token = credentials.access_token
url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'
% access_token)
# print(url)
h = httplib2.Http()
result = json.loads(h.request(url, 'GET')[1])
# If there was an error in the access token info, abort.
if result.get('error') is not None:
response = make_response(json.dumps(result.get('error')), 500)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is used for the intended user.
gplus_id = credentials.id_token['sub']
if result['user_id'] != gplus_id:
response = make_response(
json.dumps("Token's user ID doesn't match given user ID."), 401)
response.headers['Content-Type'] = 'application/json'
return response
# Verify that the access token is valid for this app.
if result['issued_to'] != CLIENT_ID:
response = make_response(
json.dumps("Token's client ID does not match app's."), 401)
print("Token's client ID does not match app's.")
response.headers['Content-Type'] = 'application/json'
return response
stored_access_token = login_session.get('access_token')
stored_gplus_id = login_session.get('gplus_id')
if stored_access_token is not None and gplus_id == stored_gplus_id:
response = make_response(json.dumps('Current user is already ' +
'connected.'),
200)
response.headers['Content-Type'] = 'application/json'
return response
# Store the access token in the session for later use.
login_session['access_token'] = credentials.access_token
login_session['gplus_id'] = gplus_id
# Get user info
userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
params = {'access_token': credentials.access_token, 'alt': 'json'}
answer = requests.get(userinfo_url, params=params)
data = answer.json()
# Set some of the session information
login_session['username'] = data["name"]
login_session['picture'] = data["picture"]
login_session['email'] = data["email"]
userid = getUserID(data["email"])
if userid is None:
userid = createUser(login_session)
output = ''
output += '<h5>Welcome, '
output += login_session['username']
output += '!</h5>'
output += '<img src="'
output += login_session['picture']
output += ' " style = "width: 255px; height: 255px;border-radius: 60px;'
output += '-webkit-border-radius: 60px;-moz-border-radius: 60px;">'
"""Flash message that the user was successfully logged out. Add BOOTSTRAP
css classes as the message category."""
flash("Logged in as %s" % login_session['username'],
'badge badge-secondary')
print("done!")
return output
@app.route('/gdisconnect')
def gdisconnect():
access_token = login_session.get('access_token')
if access_token is None:
print('Access Token is None')
errorMessage = "Current user not connected."
response = make_response(json.dumps(errorMessage), 401)
response.headers['Content-Type'] = 'application/json'
return render_template('error.html', error=errorMessage)
# DEBUGGING
# print('In gdisconnect access token is %s' % access_token)
# print('User name is: %s' % login_session['username'])
# print('Access Token is: %s' % login_session['access_token'])
url = ('https://accounts.google.com/o/oauth2/revoke?token=%s' %
login_session['access_token'])
# print('URL is: %s' % url)
h = httplib2.Http()
result = h.request(url, 'GET')[0]
# print('result is %s' % result)
# Delete the login_session variables
del login_session['access_token']
del login_session['gplus_id']
del login_session['username']
del login_session['email']
del login_session['picture']
del login_session['user_id']
if result['status'] == '200':
response = make_response(json.dumps('Successfully disconnected.'),
200)
response.headers['Content-Type'] = 'application/json'
# print (response)
"""Flash message that the user was successfully logged out. Add
BOOTSTRAP css classes as the message category."""
flash('You successfully logged out.', 'badge badge-success')
return redirect(url_for('home'))
else:
print('RESULT STATUS')
# print(result)
errorMessage = "Process failed to revoke token for given user."
response = make_response(json.dumps(errorMessage, 400))
response.headers['Content-Type'] = 'application/json'
return render_template('error.html', error=errorMessage)
# Method to check if email exists in database
def getUserID(email):
try:
user = session.query(User).filter_by(email=email).one()
login_session['user_id'] = user.id
return user.id
except:
return None
# Method to get a user's info
def getUserInfo(userid):
user = session.query(User).filter_by(id=userid).one()
return user
# Method to Create a new user
def createUser(login_session):
new_user = User(name=login_session['username'],
email=login_session['email'],
username=login_session['email'],
picture=login_session['picture'])
session.add(new_user)
session.commit()
user = session.query(User).filter_by(email=login_session['email']).one()
login_session['user_id'] = user.id
return user.id
# This page will show the entire catalog for the any user
@app.route('/')
@app.route('/catalog/')
def home():
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
# print(logged_in)
# Query all of the categories
categories = session.query(Categories).order_by("categoryName").all()
# Query the latest 5 items
"""MOST RECENT 5"""
latestItems = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl).
join(ItemPhotos).
limit(5).
all())
# Query the top 30 tags
tagCloud = session.query(ItemTags).limit(30).all()
# set the JSON link for the template page.
json_link = "/catalog/JSON"
return render_template('home_notLoggedIn.html',
categories=categories,
latestItems=latestItems,
tagCloud=tagCloud,
logged_in=logged_in,
json_link=json_link)
# JSON APIs to view full catalog
@app.route('/catalog/JSON')
def fullCatalogJSON():
items = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
Inventory.itemPrice,
Inventory.inventoryCount,
Categories.categoryName,
ItemPhotos.photoUrl).
outerjoin(Inventory, Items.itemId == Inventory.itemId).
outerjoin(ItemCategories, Items.itemId == ItemCategories.itemId).
outerjoin(Categories, ItemCategories.categoryId ==
Categories.categoryId).
outerjoin(ItemPhotos, Items.itemId == ItemPhotos.itemId).
all())
allItems = []
itemDict = {}
# Serialize the query data
for i in items:
itemDict = {
"item_id": i.itemId,
"item_name": i.itemName,
"item_desc": i.itemDescription,
"item_price": i.itemPrice,
"item_category": i.categoryName,
"item_photo": i.photoUrl,
}
allItems.append(itemDict)
# print(allItems)
return jsonify(catalogItems=allItems)
# This page will show the entire catalog for the logged in owner.
# Create the route and include only the GET method (default)
@app.route('/myCatalog')
# Create the function for displaying a restaurant's menu
def showMyItems():
if not login_session.get('access_token'):
return redirect('/')
else:
logged_in = True
ownerId = login_session["user_id"]
# Query all of the categories
categories = session.query(Categories).order_by("categoryName").all()
# Query the database for the specific restaurant information
myItems = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
Inventory.itemPrice,
Inventory.inventoryCount,
Categories.categoryName,
ItemPhotos.photoUrl).
outerjoin(Inventory, Items.itemId == Inventory.itemId).
outerjoin(ItemCategories, Items.itemId ==
ItemCategories.itemId).
outerjoin(Categories, ItemCategories.categoryId ==
Categories.categoryId).
outerjoin(ItemPhotos, Items.itemId == ItemPhotos.itemId).
filter(Items.owner == ownerId).
all())
# print(myItems)
# set the JSON link for the template page.
json_link = "/myCatalog/JSON"
# Render the menu page sending the restaurant and menu information
return render_template('myCatalogItems.html',
ownerid=ownerId,
myItems=myItems,
categories=categories,
email=login_session['email'],
logged_in=logged_in,
json_link=json_link)
# JSON APIs to view myCatalog items - based on user_id in session
@app.route('/myCatalog/JSON')
def myCatalogJSON():
if not login_session.get('access_token'):
return redirect('/')
else:
logged_in = True
ownerId = login_session["user_id"]
items = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
Inventory.itemPrice,
Inventory.inventoryCount,
Categories.categoryName,
ItemPhotos.photoUrl).
outerjoin(Inventory, Items.itemId == Inventory.itemId).
outerjoin(ItemCategories, Items.itemId == ItemCategories.itemId).
outerjoin(Categories, ItemCategories.categoryId ==
Categories.categoryId).
outerjoin(ItemPhotos, Items.itemId == ItemPhotos.itemId).
filter(Items.owner == ownerId).
all())
allItems = []
itemDict = {}
for i in items:
itemDict = {
"item_id": i.itemId,
"item_name": i.itemName,
"item_desc": i.itemDescription,
"item_price": i.itemPrice,
"item_category": i.categoryName,
"item_photo": i.photoUrl,
}
allItems.append(itemDict)
# print(allItems)
return jsonify(myCatalogItems=allItems)
# This page will display all items of selected category for non-logged-in user
@app.route('/catalog/<categoryName>/')
def showCategoryItems(categoryName):
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
# Query all of the categories
categories = session.query(Categories).order_by("categoryName").all()
# Query the latest 6 items
categoryItems = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl,
ItemCategories.categoryId,
Categories.categoryName).
join(ItemPhotos).
join(ItemCategories).
join(Categories).
filter_by(categoryName=categoryName.title()).
all())
# Display the number of records found
if len(categoryItems) == 0:
countMessage = "No items were found in this category."
else:
countMessage = "%s items found." % len(categoryItems)
# FOR DUEBUG - Print the object in the console
# Query the top 30 tags
tagCloud = session.query(ItemTags).limit(30).all()
"""ADD RANDOM IMAGES"""
json_link = "/catalog/%s/JSON" % categoryName
return render_template('categoryItems_notLoggedIn.html',
categories=categories,
categoryItems=categoryItems,
catName=categoryName,
tagCloud=tagCloud,
countMessage=countMessage,
logged_in=logged_in,
json_link=json_link)
# JSON APIs to view myCatalog items - based on user_id in session
@app.route('/catalog/<categoryName>/JSON')
def showCategoryItemsJSON(categoryName):
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
# Query the latest 6 items
categoryItems = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
Inventory.itemPrice,
Inventory.inventoryCount,
Categories.categoryName,
ItemPhotos.photoUrl).
outerjoin(Inventory, Items.itemId == Inventory.itemId).
outerjoin(ItemCategories, Items.itemId ==
ItemCategories.itemId).
outerjoin(ItemPhotos, Items.itemId == ItemPhotos.itemId).
outerjoin(Categories, ItemCategories.categoryId ==
Categories.categoryId).
filter_by(categoryName=categoryName.title()).
all())
allItems = []
itemDict = {}
for i in categoryItems:
itemDict = {
"item_id": i.itemId,
"item_name": i.itemName,
"item_desc": i.itemDescription,
"item_price": i.itemPrice,
"item_inventory": i.inventoryCount,
"item_category": i.categoryName,
"item_photo": i.photoUrl,
}
allItems.append(itemDict)
# print(allItems)
return jsonify(categoryItems=allItems)
# This page will display all items of a selected tag for a non-logged-in user.
@app.route('/catalog/tags/<tag>/')
def showTaggedItems(tag):
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
# Query all of the categories
categories = session.query(Categories).order_by("categoryName").all()
# Query the items with the supplied tag
taggedItems = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl,
ItemTags.tag,).
join(ItemPhotos).
join(ItemTags).
filter_by(tag=tag).
all())
# FOR DUEBUG - Print the object in the console
# print(taggedItems)
# Display a count of the number of records found
if len(taggedItems) == 0:
countMessage = "No items were found."
else:
countMessage = "%s items found." % len(taggedItems)
# Query the top 30 tags
tagCloud = session.query(ItemTags).limit(30).all()
json_link = "/catalog/tags/%s/JSON" % tag
return render_template('taggedItems_notLoggedIn.html',
categories=categories,
taggedItems=taggedItems,
tagCloud=tagCloud,
tagName=tag,
countMessage=countMessage,
logged_in=logged_in,
json_link=json_link)
# JSON APIs to view myCatalog items - based on user_id in session
@app.route('/catalog/tags/<tag>/JSON')
def showTaggedItemsJSON(tag):
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
# Query the items with the supplied tag
taggedItems = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl,
ItemTags.tag).
join(ItemPhotos).
join(ItemTags).
filter_by(tag=tag).
all())
allItems = []
itemDict = {}
for i in taggedItems:
itemDict = {
"item_id": i.itemId,
"item_name": i.itemName,
"item_desc": i.itemDescription,
"item_photo": i.photoUrl,
}
allItems.append(itemDict)
# print(allItems)
return jsonify(categoryItems=allItems)
# This page will show the full item details for a non-logged-in user.
@app.route('/catalog/items/<int:itemId>')
def showItemDetails(itemId):
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
# Query all of the categories
categories = session.query(Categories).order_by("categoryName").all()
# Query the specific item based on itemId
item = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl,
Inventory.itemPrice,
Inventory.inventoryCount).
outerjoin(ItemPhotos).
outerjoin(Inventory).
filter(Items.itemId == int(itemId)).
first())
# FOR DUEBUG - Print the object in the console
# print(item)
# Display a count of the number of records found
if not item:
countMessage = "Item not found."
countMessageClass = "badge badge-warning"
display = "none"
else:
countMessage = ""
countMessageClass = ""
display = "initial"
# FOR DUEBUG - Print the object in the console
# for i in taggedItems:
# print("ItemID: %s" % i[0])
# print("ItemUrl: %s" % i[1])
# Query the top 30 tags
tagCloud = session.query(ItemTags).limit(30).all()
json_link = "/catalog/items/%s/JSON" % str(itemId)
return render_template('item_notLoggedIn.html',
categories=categories,
tagCloud=tagCloud,
itemDisplay=display,
item=item,
countMessageClass=countMessageClass,
countMessage=countMessage,
logged_in=logged_in,
json_link=json_link)
# JSON APIs to view myCatalog items - based on user_id in session
@app.route('/catalog/items/<int:itemId>/JSON')
def itemDetailsJSON(itemId):
if not login_session.get('access_token'):
logged_in = False
else:
logged_in = True
items = (session.query(Items.itemId,
Items.itemName,
Items.itemDescription,
Inventory.itemPrice,
Inventory.inventoryCount,
Categories.categoryName,
ItemPhotos.photoUrl).
outerjoin(Inventory, Items.itemId == Inventory.itemId).
outerjoin(ItemCategories, Items.itemId == ItemCategories.itemId).
outerjoin(Categories, ItemCategories.categoryId ==
Categories.categoryId).
outerjoin(ItemPhotos, Items.itemId == ItemPhotos.itemId).
filter(Items.itemId == int(itemId)).
all())
allItems = []
itemDict = {}
for i in items:
itemDict = {
"item_id": i.itemId,
"item_name": i.itemName,
"item_desc": i.itemDescription,
"item_price": i.itemPrice,
"item_category": i.categoryName,
"item_photo": i.photoUrl,
}
allItems.append(itemDict)
# print(allItems)
return jsonify(ItemDetails=allItems)
# "This page will show a form for adding a new item to a personal catalog."
# Create the route and include both the POST and GET methods
@app.route('/catalog/addItem', methods=['GET', 'POST'])
def addCatalogItem():
if not login_session.get('access_token'):
return redirect('/')
else:
logged_in = True
ownerId = login_session["user_id"]
# Query all of the categories
categories = session.query(Categories).order_by("categoryName").all()
# POST methods actions
if request.method == 'POST':
# Set the name of the new restaurant into the dictionary
new_item = Items(itemName=request.form['item_name'],
itemDescription=request.form['item_description'],
owner=ownerId,
added=currentDateTime,
modified=currentDateTime,
status='A')
# Add it to the session
session.add(new_item)
# Commit the addition to the database
session.commit()
addedItem = session.query(Items).order_by(Items.itemId.desc()).first()
"""Flash message that the item was successfully added. Add BOOTSTRAP
css classes as the message category."""
flash('New item was successfully added! (%s)' % addedItem.itemName,
'badge badge-success')
new_cat = request.form['item_category']
new_count = request.form['item_inventory']
new_price = request.form['item_price']
new_item_category = ItemCategories(categoryId=new_cat,
itemId=addedItem.itemId)
new_item_inventory = Inventory(itemId=addedItem.itemId,
inventoryCount=new_count,
itemPrice=new_price,
lastUpdated=currentDateTime)
session.add(new_item_category)
session.add(new_item_inventory)
session.commit()
# Item Tags - Outside of scope of this project - Do later
# Item Photo - Outside of scope of this project - Do later
# Redirect the user back to the main Restaurants page
return redirect(url_for('showMyItems'))
# GET method actions
else:
# Display the Add New Restaurant form page
return render_template('addItem_LoggedIn.html',
categories=categories,
email=login_session['email'],
logged_in=logged_in)
# Edit a catalog item
@app.route('/catalog/items/<int:itemId>/update/', methods=['GET', 'POST'])
def editItem(itemId):
# If the logged in user is not the owner of the item record, redirect home
if not login_session.get('access_token'):
"""Flash message that the item was successfully added. Add BOOTSTRAP
css classes as the message category."""
flash('You\'re not authorized to edit/delete items from the database',
'badge badge-warning')
return redirect('/')
else:
logged_in = True
ownerId = login_session["user_id"]
# Query all of the categories for the navigation bar
categories = session.query(Categories).order_by("categoryName").all()
# Query the item to edit
editedItem = (session.query(Items.owner,
Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl,
Inventory.itemPrice,
ItemCategories.categoryId,
Inventory.inventoryCount).
outerjoin(ItemCategories, Items.itemId ==
ItemCategories.itemId).
outerjoin(ItemPhotos, Items.itemId == ItemPhotos.itemId).
outerjoin(Inventory, Items.itemId == Inventory.itemId).
filter(Items.itemId == int(itemId)).
filter(Items.owner == int(ownerId)).
first())
if not editedItem or editedItem.owner != ownerId:
"""Flash message that the item was successfully added. Add BOOTSTRAP
css classes as the message category."""
flash('You\'re not authorized to edit/delete this item.',
'badge badge-warning')
return redirect(url_for('showMyItems'))
# print(editedItem)
if request.method == 'POST':
# Save edits to the items table
if request.form['item_name']:
print(request.form['item_name'])
itemToEdit = (session.query(Items).
filter(Items.itemId == int(itemId)).
filter(Items.owner == int(ownerId)).
all())
for i in itemToEdit:
i.itemName = request.form['item_name']
i.itemDescription = request.form['item_description']
session.commit()
# Save edits to the itemCategory table
itemCategory = (session.query(ItemCategories).
filter(ItemCategories.itemId == int(itemId)).
all())
for i in itemCategory:
i.categoryId = request.form['item_category']
session.commit()
# Save edits to the inventory (price and count) table
itemInventory = (session.query(Inventory).
filter(Inventory.itemId == int(itemId)).
all())
for i in itemInventory:
i.inventoryCount = request.form['item_inventory']
i.itemPrice = request.form['item_price']
i.lastUpdated = currentDateTime
# Commit the edits
session.commit()
"""Flash message that the item was successfully added. Add
BOOTSTRAP css classes as the message category."""
flash('Item was successfully edited (%s)' % editedItem.itemName,
'badge badge-success')
return redirect(url_for('showMyItems'))
else:
return render_template('editItem_LoggedIn.html',
categories=categories,
item=editedItem,
logged_in=logged_in)
# Edit a restaurant
@app.route('/catalog/items/<int:itemId>/delete/', methods=['POST'])
def deleteItem(itemId):
if not login_session.get('access_token'):
return redirect('/')
else:
logged_in = True
ownerId = login_session["user_id"]
# Query the appropriate tables for the specified item to delete
deleteItem = (session.query(Items.owner,
Items.itemId,
Items.itemName,
Items.itemDescription,
ItemPhotos.photoUrl,
Inventory.itemPrice,
ItemCategories.categoryId,
Inventory.inventoryCount).
outerjoin(ItemCategories).
outerjoin(ItemPhotos).
outerjoin(Inventory).
filter(Items.itemId == int(itemId)).
filter(Items.owner == int(ownerId)).
first())
# If the user is not the owner of the restaurant record, redirect to home
if deleteItem.owner != login_session.get('user_id'):
return redirect(url_for('showMyItems'))
if request.method == 'POST':
session.query(Items).filter(Items.itemId == int(itemId)).delete()
session.commit()
"""Flash message that the item was successfully added. Add BOOTSTRAP
css classes as the message category."""
flash('Item was successfully deleted (%s)' % deleteItem.itemName,
'badge badge-success')
return redirect(url_for('showMyItems'))
else:
return redirect(url_for('showMyItems'))
if __name__ == '__main__':
app.secret_key = 'dja90d8fa0sdnfasidpfaksjfd9s8ad'
app.debug = True
app.run(host='0.0.0.0', port=8000) # , ssl_context=('cert.pem', 'key.pem')