/
FlaskStuff.py
388 lines (243 loc) · 11.1 KB
/
FlaskStuff.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
from flask import Flask, redirect, session, flash
from flask.globals import request
from flask.templating import render_template
import Database
from Config import Config
from entities.Users import User
from entities.Products import Product
from forms import NewProductForm
from forms.LoginForm import LoginForm
from forms.RegisterForm import RegisterForm
from forms.UpdateForm import UpdateForm
from forms.NewProductForm import NewProductForm
from forms.UpdateProductForm import UpdateProductForm
from werkzeug.utils import secure_filename
import os
app = Flask(__name__)
app.config.from_object(Config)
app.config['MAX_CONTENT_LENGTH'] = Config.MAX_CONTENT_LENGTH
app.config['UPLOAD_EXTENSIONS'] = Config.UPLOAD_EXTENSIONS
app.config['UPLOAD_PATH'] = Config.IMAGE_UPLOAD_FOLDER
@app.route('/')
def index():
if 'username' not in session:
return render_template('index.html', title="Home")
name = session.get('username')
user_details = Database.user_details_by_name(name)
user_products = Database.products_owned_by_user(name)
info = make_info_message(name, user_products)
return render_template('welcome.html', title="Hello", user=user_details, products=user_products, messages=info)
@app.route('/login', methods=['GET', 'POST'])
def login():
if 'username' in session:
return redirect(request.referrer)
form = LoginForm()
if form.validate_on_submit():
name = form.username.data
exists = Database.user_exists(name)
if exists:
details = Database.user_details_by_name(name)
u = User(details[0], details[1], details[2])
# if user is already logged in get their name and if they have admin access, otherwise add it
if 'username' in session:
session['username'] = session.get('username')
session['access'] = session.get('access')
else:
session['username'] = details[0]
session['access'] = u.is_admin(details[2])
return redirect('/')
else:
flash("User not found!", 'noUser')
return redirect('/login')
return render_template('login.html', title="Login", form=form)
@app.route('/register', methods=['GET', 'POST'])
def register():
if 'username' not in session:
return redirect(request.referrer)
form = RegisterForm()
if form.validate_on_submit():
name = form.username.data
password = form.password.data
exists = Database.user_exists(name)
if not exists:
user = User(name, password)
if session.get('access'):
user.make_user_admin()
Database.insert_user(user)
return redirect('/')
else:
flash("Username already taken!", 'userTakenMsg')
return redirect('/register')
return render_template('register.html', title='Register', form=form)
@app.route('/logout')
def logout():
if 'username' not in session:
return redirect(request.referrer)
session.pop('username', None)
session.pop('access', None)
return redirect('/')
@app.route('/listUsers')
def list_all_users():
if 'username' not in session:
return redirect(request.referrer)
all_users = Database.get_users()
return render_template('viewAllUsers.html', title="Viewing Users", users=all_users)
@app.route('/viewOneUser/<string:name>')
def view_one_user(name):
if 'username' not in session:
return redirect(request.referrer)
user = Database.user_details_by_name(name)
return render_template('viewOneUser.html', title="Viewing User", user=user)
@app.route('/editUser/<string:name>', methods=['GET', 'POST'])
def edit_user(name):
if 'username' not in session:
return redirect(request.referrer)
index_pg = 'http://127.0.0.1:5000/'
previous_pg = request.referrer
users = Database.get_name_of_users()
# If they come from the index page
if previous_pg == index_pg:
users = [name] # Only the logged in user is to be displayed
form = UpdateForm()
if form.is_submitted():
old_name = form.nameToChange.data
new_name = form.newUsername.data
new_password = form.newPassword.data
role = "user"
# If true is returned then make admin
if form.newRole.data:
role = "admin"
Database.update_user(old_name, new_name, new_password, role) # User is updated with these changes
return redirect('/listUsers')
form.nameToChange.choices = users # All the available names are made to be possible choices in the form
form.nameToChange.default = name # The name of the user in clicked edit button's row is made default
form.process() # Processes the change in the default
return render_template('editUser.html', title="Editing User", form=form)
@app.route('/deleteUser/<string:name>', methods=['GET', 'POST'])
def delete_user(name):
if 'username' not in session:
return redirect(request.referrer)
Database.delete_user(name)
return redirect('/listUsers')
@app.route('/listProducts')
def list_products():
all_products = Database.get_products()
amount = len(all_products)
msg = "The details for the product, are shown below:"
if amount > 1:
msg = f"The details for the {amount} products are shown below:"
return render_template('viewAllProducts.html', title="Viewing Catalog", products=all_products, message=msg)
@app.route('/newProduct', methods=['GET', 'POST'])
def create_product():
if 'username' not in session:
return redirect(request.referrer)
form = NewProductForm()
all_users = Database.get_name_of_users()
form.productOwner.choices = all_users # All the available names are made to be possible choices in the form
name = session.get('username')
form.productOwner.default = name # The name of the user in clicked edit button's row is made default
form.process() # Processes the change in the default
if request.method == 'POST' and form.is_submitted():
owner = request.form.get("productOwner")
product_name = request.form.get("productName")
# Gets the file name from within the file in form of the posted request
file = request.files['imageFile']
filename = secure_filename(file.filename)
# Saves the file to the designated folder
file.save(os.path.join(app.config["UPLOAD_PATH"], filename))
price = request.form.get("productPrice")
product = Product(product_name, price, filename, owner)
Database.insert_product(product)
return redirect('/listProduct')
return render_template('createProduct.html', title='New Product', form=form)
@app.route('/viewOneProduct/<string:name>')
def view_one_product(name):
product = Database.product_details_by_name(name)
return render_template('viewOneProduct.html', title="Viewing Product", product=product)
@app.route('/editProduct/<string:name>', methods=['GET', 'POST'])
def edit_product(name):
if 'username' not in session:
return redirect(request.referrer)
users = Database.get_name_of_users()
form = UpdateProductForm()
product = Database.product_details_by_name(name)
name_product = product[0]
product_price = product[1]
product_owner = product[3]
form.productOwner.choices = users # All the available names are made to be possible choices in the form
# Forms default values set
form.productOwner.default = product_owner
form.productName.default = name_product
form.productPrice.default = product_price
form.imageFile.default = product[2]
form.process() # Processes the change in the default
if request.method == 'POST' and form.is_submitted():
owner = request.form.get("productOwner")
product_name = request.form.get("productName")
# Gets the file name from within the file in form of the posted request
file = request.files['imageFile']
filename = secure_filename(file.filename)
# Saves the file to the designated folder
file.save(os.path.join(app.config["UPLOAD_PATH"], filename))
price = request.form.get("productPrice")
product = Product(product_name, price, filename, owner)
Database.update_product(name_product, product)
return redirect('/listProducts')
return render_template('editProduct.html', title="Editing Product", form=form)
@app.route('/viewProducts/<string:name>')
def view_users_products(name):
# if name passed ends with the curly bracket then its removed
if name[len(name) - 1] == "}":
name = name[0: len(name) - 1]
user_exists = Database.user_exists(name)
if not user_exists or 'username' not in session:
return redirect('/')
all_products = Database.products_owned_by_user(name)
info = make_info_message(name, all_products)
return render_template('viewUserProducts.html', title=(name+"'s Products"), products=all_products, messages=info)
@app.route('/deleteProduct/<string:name>', methods=['GET'])
def delete_product(name):
if 'username' not in session:
return redirect(request.referrer)
Database.delete_product(name)
return redirect("/listProducts")
@app.route('/viewProducts/productsOverview')
def view_products_overview():
if 'username' not in session:
return redirect('/')
unique_users = Database.unique_users_list()
details = []
for user in unique_users:
users_products = Database.name_of_products_owned_by_user(user)
products_prices = []
total = 0
for users_product in users_products:
price = Database.price_of_product_by_name_and_owner(user, users_product)
products_prices.append(price)
total += price
details.append([user, users_products, products_prices, total])
return render_template('productsOverview.html', title="Overview of Products", items=details)
@app.route('/resetDatabase', methods=['GET', 'POST'])
def refresh_db():
if ('username' not in session) and ('access' not in session):
return redirect(request.referrer)
Database.drop_tables()
Database.create_tables()
Database.refresh_db()
session.pop('username', None)
session.pop('access', None)
return redirect('/')
def make_info_message(name, all_products):
amount = len(all_products)
msg = f"The details for {name}'s product, are shown below:"
total = Database.users_total_cost(name)
msg2 = f"Product total comes to €{total}"
info = [msg, msg2]
if amount > 1:
msg = f"The details for {name}'s {amount} products are shown below:"
msg2 = f"Products total comes to €{total}"
info = [msg, msg2]
return info
# Run the application
if __name__ == "__main__":
app.run(debug=True)