-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1221 lines (977 loc) · 66.8 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
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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import csv
import calendar
import datetime
import psycopg2
import psycopg2.extras
import pytz
import requests
import urllib
from flask import Flask, flash, jsonify, redirect, render_template, request, session, url_for
from flask_session import Session
from werkzeug.security import check_password_hash, generate_password_hash
from functools import wraps
# WEATHER API
import openmeteo_requests
import requests_cache
import pandas as pd
from retry_requests import retry
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
db = psycopg2.connect(host=os.environ['DB_HOST'],
port=int(os.environ['DB_PORT']),
database=os.environ['DB_NAME'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'])
if __name__ == "__main__":
port = int(os.environ.get("PORT", 10000))
app.run(host="0.0.0.0", port=port)
@app.after_request
def after_request(response):
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Expires"] = 0
response.headers["Pragma"] = "no-cache"
return response
def error(message, code):
with db.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE username = %s", ('admin',))
admin = cur.fetchall()
admin_id = None
if len(admin) == 1:
admin_id = admin[0]["user_id"]
cur.execute("SELECT * FROM users WHERE user_id = %s", (session["user_id"],))
username = cur.fetchall()[0]["username"]
final_message = "Error " + str(code) + ": " + message
return render_template("error.html", final_message=final_message, code=code, admin_id=admin_id, username=username)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
@app.route("/", methods=["GET", "POST"])
@login_required
def index():
with db.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE username = %s", ('admin',))
admin = cur.fetchall()
admin_id = None
if len(admin) == 1:
admin_id = admin[0]["user_id"]
cur.execute("SELECT * FROM users WHERE user_id = %s", (session["user_id"],))
username = cur.fetchall()[0]["username"]
if request.method == "POST":
if request.form.get("add_freetext_plant_button"):
if not request.form.get("plant_name_add"):
return error("Must provide plant name.", 400)
elif not request.form.get("duration_to_maturity_months_add"):
return error("Must provide duration to maturity (months).", 400)
elif not request.form.get("plant_spacing_metres_add"):
return error("Must provide spacing (metres).", 400)
elif not request.form.get("perennial_or_annual_add"):
return error("Must specify perennial or annual.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_add")):
return error("Plant name must be alphabetical.", 400)
try:
duration_to_maturity_months_add = int(request.form.get("duration_to_maturity_months_add"))
except ValueError:
return error("Duration to maturity (months) must be integer.", 400)
if duration_to_maturity_months_add <= 0:
return error("Duration to maturity (months) must be positive number.", 400)
try:
plant_spacing_metres_add = int(request.form.get("plant_spacing_metres_add"))
except ValueError:
try:
plant_spacing_metres_add = float(request.form.get("plant_spacing_metres_add"))
except ValueError:
return error("Spacing (metres) must be integer or decimal number.", 400)
if plant_spacing_metres_add <= 0:
return error("Spacing (metres) must be positive number.", 400)
string_plant_spacing_metres_add = str(plant_spacing_metres_add)
decimal_places = string_plant_spacing_metres_add[::-1].find(".")
if decimal_places == -1:
metres_squared_required_add = round(plant_spacing_metres_add ** 2, 0)
elif decimal_places == 1:
metres_squared_required_add = round(plant_spacing_metres_add ** 2, 2)
elif decimal_places == 2:
metres_squared_required_add = round(plant_spacing_metres_add ** 2, 4)
else:
metres_squared_required_add = round(plant_spacing_metres_add ** 2, 6)
if request.form.get("perennial_or_annual_add") != "perennial" and request.form.get("perennial_or_annual_add") != "annual":
return error("Must select either perennial or annual.", 400)
january_add = "no"
february_add = "no"
march_add = "no"
april_add = "no"
may_add = "no"
june_add = "no"
july_add = "no"
august_add = "no"
september_add = "no"
october_add = "no"
november_add = "no"
december_add = "no"
if request.form.get("january_add") == "yes":
january_add = "yes"
if request.form.get("february_add") == "yes":
february_add = "yes"
if request.form.get("march_add") == "yes":
march_add = "yes"
if request.form.get("april_add") == "yes":
april_add = "yes"
if request.form.get("may_add") == "yes":
may_add = "yes"
if request.form.get("june_add") == "yes":
june_add = "yes"
if request.form.get("july_add") == "yes":
july_add = "yes"
if request.form.get("august_add") == "yes":
august_add = "yes"
if request.form.get("september_add") == "yes":
september_add = "yes"
if request.form.get("october_add") == "yes":
october_add = "yes"
if request.form.get("november_add") == "yes":
november_add = "yes"
if request.form.get("december_add") == "yes":
december_add = "yes"
cur.execute("SELECT plant_id FROM freetext_plants WHERE plant_name = %s", (request.form.get("plant_name_add").lower(),))
try:
plant_id = cur.fetchone()["plant_id"]
return error("Freetext plant already exists.", 400)
except (TypeError):
pass
cur.execute("INSERT INTO freetext_plants (user_id, plant_name, duration_to_maturity_months, plant_spacing_metres, metres_squared_required, perennial_or_annual, january, february, march, april, may, june, july, august, september, october, november, december) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", (int(session["user_id"]), request.form.get("plant_name_add").lower(), duration_to_maturity_months_add, plant_spacing_metres_add, metres_squared_required_add, request.form.get("perennial_or_annual_add"), january_add, february_add, march_add, april_add, may_add, june_add, july_add, august_add, september_add, october_add, november_add, december_add,))
db.commit()
return redirect("/")
if request.form.get("remove_freetext_plant_button"):
if not request.form.get("plant_name_remove"):
return error("Must provide plant name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_remove")):
return error("Plant name must be alphabetical.", 400)
cur.execute("SELECT freetext_plants.plant_name FROM freetext_plants WHERE freetext_plants.user_id = %s", (int(session["user_id"]),))
freetext_plant_names_from_user = cur.fetchall()
is_plant_in_db = False
for i in range(len(freetext_plant_names_from_user)):
if freetext_plant_names_from_user[i]["plant_name"] == request.form.get("plant_name_remove").lower():
is_plant_in_db = True
if is_plant_in_db == False:
return error("Plant name not found.", 400)
cur.execute("SELECT plant_id FROM freetext_plants WHERE plant_name = %s AND user_id = %s", (request.form.get("plant_name_remove").lower(), int(session["user_id"]),))
plant_id = cur.fetchall()
for i in range(len(plant_id)):
cur.execute("DELETE FROM freetext_plants WHERE plant_id = %s", (plant_id[i]["plant_id"],))
cur.execute("DELETE FROM planted_in_gardens WHERE plant_id = %s", (plant_id[i]["plant_id"],))
cur.execute("DELETE FROM companion_friends WHERE plant_id_a = %s OR plant_id_b = %s", (plant_id[i]["plant_id"], plant_id[i]["plant_id"]))
cur.execute("DELETE FROM companion_enemies WHERE plant_id_a = %s OR plant_id_b = %s", (plant_id[i]["plant_id"], plant_id[i]["plant_id"]))
db.commit()
return redirect("/")
if request.form.get("add_new_garden_button"):
if not request.form.get("add_new_garden_name"):
return error("Must provide garden name.", 400)
elif not request.form.get("add_new_garden_size"):
return error("Must provide garden size (metres squared).", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("add_new_garden_name")):
return error("Garden name must be alphabetical.", 400)
try:
add_new_garden_size = int(request.form.get("add_new_garden_size"))
except ValueError:
return error("Garden size (metres squared) must be integer.", 400)
if add_new_garden_size <= 0:
return error("Garden size (metres squared) must be integer.", 400)
cur.execute("SELECT garden_name FROM gardens WHERE user_id = %s", (int(session["user_id"]),))
garden_names_user = cur.fetchall()
for i in range(len(garden_names_user)):
if garden_names_user[i]["garden_name"] == request.form.get("add_new_garden_name").lower():
return error("You already have a garden with that name.", 400)
cur.execute("INSERT INTO gardens (garden_name, garden_size_metres_squared, user_id) VALUES (%s, %s, %s)", (request.form.get("add_new_garden_name").lower(), request.form.get("add_new_garden_size"), int(session["user_id"]),))
db.commit()
return redirect("/")
if request.form.get("remove_garden_button"):
if not request.form.get("remove_garden_name"):
return error("Must provide garden name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("remove_garden_name")):
return error("Garden name must be alphabetical.", 400)
cur.execute("SELECT garden_name FROM gardens WHERE user_id = %s", (int(session["user_id"]),))
garden_names = cur.fetchall()
is_plant_in_db = False
for i in range(len(garden_names)):
if garden_names[i]["garden_name"] == request.form.get("remove_garden_name").lower():
is_plant_in_db = True
if is_plant_in_db == False:
return error("You don't have a garden with that name.", 400)
cur.execute("SELECT garden_id FROM gardens WHERE garden_name = %s AND user_id = %s", (request.form.get("remove_garden_name").lower(), int(session["user_id"]),))
garden_id = cur.fetchall()
for i in range(len(garden_id)):
cur.execute("DELETE FROM gardens WHERE garden_id = %s", (garden_id[i]["garden_id"],))
cur.execute("DELETE FROM planted_in_gardens WHERE garden_id = %s", (garden_id[i]["garden_id"],))
db.commit()
return redirect("/")
if request.form.get("add_plants_to_garden_button"):
if not request.form.get("add_plants_to_garden_garden_name"):
return error("Must provide garden name.", 400)
if not request.form.get("add_plants_to_garden_plant_name"):
return error("Must provide plant name.", 400)
if not request.form.get("add_plants_to_garden_number_of_plants"):
return error("Must provide number of plants to add.", 400)
if not request.form.get("add_plants_to_garden_month_planted"):
return error("Must indicate in which month planted.", 400)
if not request.form.get("add_plants_to_garden_months_to_remain_planted"):
return error("Must provide number of months to remain planted.", 400)
if not request.form.get("add_plants_to_garden_freetext"):
return error("Must indicate whether plant is freetext.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("add_plants_to_garden_garden_name")):
return error("Garden name must be alphabetical.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("add_plants_to_garden_plant_name")):
return error("Plant name must be alphabetical.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("add_plants_to_garden_month_planted")):
return error("Month planted must be alphabetical.", 400)
try:
add_plants_to_garden_number_of_plants = int(request.form.get("add_plants_to_garden_number_of_plants"))
except ValueError:
return error("Number of plants to add must be integer.", 400)
if add_plants_to_garden_number_of_plants <= 0:
return error("Number of months this plant was planted for must be positive number.", 400)
try:
add_plants_to_garden_months_to_remain_planted = int(request.form.get("add_plants_to_garden_months_to_remain_planted"))
except ValueError:
return error("Number of months to remain planted must be integer.", 400)
if add_plants_to_garden_months_to_remain_planted <= 0:
return error("Number of months to remain planted must be positive number.", 400)
if request.form.get("add_plants_to_garden_freetext") != "yes" and request.form.get("add_plants_to_garden_freetext") != "no":
return error("Is the plant freetext? Must select either yes or no.", 400)
garden_id = None
cur.execute("SELECT garden_id FROM gardens WHERE user_id = %s AND garden_name = %s", (int(session["user_id"]), request.form.get("add_plants_to_garden_garden_name").lower(),))
try:
garden_id = cur.fetchone()["garden_id"]
except (TypeError):
return error("Garden name not found.", 400)
if garden_id == None:
return error("Garden name not found.", 400)
plant_id = None
if request.form.get("add_plants_to_garden_freetext") == 'no':
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("add_plants_to_garden_plant_name").lower(),))
try:
plant_id = cur.fetchone()["plant_id"]
except (TypeError):
return error("Plant not found.", 400)
elif request.form.get("add_plants_to_garden_freetext") == 'yes':
cur.execute("SELECT plant_id FROM freetext_plants WHERE plant_name = %s", (request.form.get("add_plants_to_garden_plant_name").lower(),))
try:
plant_id = cur.fetchone()["plant_id"]
except (TypeError):
return error("Plant not found.", 400)
if plant_id == None:
return error("Plant not found.", 400)
months_of_year = []
for j in range(1, 13):
months_of_year.append(calendar.month_name[j].lower())
if request.form.get("add_plants_to_garden_month_planted") not in months_of_year:
return error("Month to be planted invalid.", 400)
if request.form.get("add_plants_to_garden_freetext") != 'yes' and request.form.get("add_plants_to_garden_freetext") != 'no':
return error("Is the plant freetext? Must select either yes or no.", 400)
cur.execute("INSERT INTO planted_in_gardens (plant_id, garden_id, number_of_plants, month_planted, months_to_remain_planted, freetext) VALUES (%s, %s, %s, %s, %s, %s)", (plant_id, garden_id, request.form.get("add_plants_to_garden_number_of_plants"), request.form.get("add_plants_to_garden_month_planted"), request.form.get("add_plants_to_garden_months_to_remain_planted"), request.form.get("add_plants_to_garden_freetext")),)
db.commit()
return redirect("/")
if request.form.get("remove_plants_from_garden_button"):
if not request.form.get("remove_plants_from_garden_garden_name"):
return error("Must provide garden name.", 400)
if not request.form.get("remove_plants_from_garden_plant_name"):
return error("Must provide plant name.", 400)
if not request.form.get("remove_plants_from_garden_freetext"):
return error("Is the plant freetext? Must select either yes or no.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("remove_plants_from_garden_garden_name")):
return error("Garden name must be alphabetical.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("remove_plants_from_garden_plant_name")):
return error("Plant name must be alphabetical.", 400)
if request.form.get("remove_plants_from_garden_freetext") != "yes" and request.form.get("remove_plants_from_garden_freetext") != "no":
return error("Is the plant freetext? Must select either yes or no.", 400)
cur.execute("SELECT garden_id FROM gardens WHERE user_id = %s AND garden_name = %s", (int(session["user_id"]), request.form.get("remove_plants_from_garden_garden_name").lower(),))
garden_ids = cur.fetchall()
if len(garden_ids) == 0:
return error("Garden name not found.", 400)
garden_id = garden_ids[0]["garden_id"]
plant_id = None
if request.form.get("remove_plants_from_garden_freetext") == 'no':
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("remove_plants_from_garden_plant_name").lower(),))
try:
plant_id = cur.fetchone()["plant_id"]
except (TypeError):
return error("Plant not found.", 400)
elif request.form.get("remove_plants_from_garden_freetext") == 'yes':
cur.execute("SELECT plant_id FROM freetext_plants WHERE plant_name = %s", (request.form.get("remove_plants_from_garden_plant_name").lower(),))
result = cur.fetchone()
plant_id = result["plant_id"]
if plant_id == None:
return error("Plant not found.", 400)
cur.execute("DELETE FROM planted_in_gardens WHERE garden_id = %s AND plant_id = %s", (garden_id, plant_id,))
db.commit()
return redirect("/")
return redirect ("/")
else:
cur.execute("SELECT garden_id, garden_name, garden_size_metres_squared FROM gardens WHERE user_id = %s", (int(session["user_id"]),))
garden_ids_from_user = cur.fetchall()
number_of_gardens_from_user = len(garden_ids_from_user)
planted_gardens_from_user = []
for i in range(number_of_gardens_from_user):
planted_gardens_from_user.append([])
months_of_year = []
for i in range(1, 13):
months_of_year.append(calendar.month_name[i].lower())
total_different_plants_in_garden = []
all_plant_names_in_garden = []
space_remaining_each_month = []
for i in range(number_of_gardens_from_user):
total_different_plants_in_garden.append([])
all_plant_names_in_garden.append([])
space_remaining_each_month.append([])
if number_of_gardens_from_user > 0:
for i in range(number_of_gardens_from_user):
plants_planted_each_month_of_year = []
plants_growing_each_month_of_year = []
for j in range(12):
plants_planted_each_month_of_year.append([])
plants_growing_each_month_of_year.append([])
space_remaining_each_month[i].append([])
for j in range(12):
cur.execute("SELECT plants.plant_name, planted_in_gardens.number_of_plants, planted_in_gardens.months_to_remain_planted, plants.metres_squared_required, plants.perennial_or_annual FROM gardens INNER JOIN planted_in_gardens ON gardens.garden_id = planted_in_gardens.garden_id INNER JOIN plants ON planted_in_gardens.plant_id = plants.plant_id WHERE planted_in_gardens.month_planted = %s AND gardens.garden_id = %s AND gardens.user_id = %s AND planted_in_gardens.freetext = 'no'", (months_of_year[j], int(garden_ids_from_user[i]["garden_id"]), int(session["user_id"]),))
monthly_plants_nonfreetext = cur.fetchall()
cur.execute("SELECT freetext_plants.plant_name, planted_in_gardens.number_of_plants, planted_in_gardens.months_to_remain_planted, freetext_plants.metres_squared_required, freetext_plants.perennial_or_annual FROM gardens INNER JOIN planted_in_gardens ON gardens.garden_id = planted_in_gardens.garden_id INNER JOIN freetext_plants ON planted_in_gardens.plant_id = freetext_plants.plant_id WHERE planted_in_gardens.month_planted = %s AND gardens.garden_id = %s AND gardens.user_id = %s AND planted_in_gardens.freetext = 'yes'", (months_of_year[j], int(garden_ids_from_user[i]["garden_id"]), int(session["user_id"]),))
monthly_plants_freetext = cur.fetchall()
for k in range(len(monthly_plants_nonfreetext)):
plants_planted_each_month_of_year[j].append(monthly_plants_nonfreetext[k])
for k in range(len(monthly_plants_freetext)):
plants_planted_each_month_of_year[j].append(monthly_plants_freetext[k])
for k in range(len(plants_planted_each_month_of_year[j])):
plant_months_to_remain_planted = int(plants_planted_each_month_of_year[j][k]["months_to_remain_planted"])
plant_perennal_or_annual = plants_planted_each_month_of_year[j][k]["perennial_or_annual"]
if plant_perennal_or_annual == "perennial":
for l in range(j, 12):
plants_growing_each_month_of_year[l].append(plants_planted_each_month_of_year[j][k])
elif plant_perennal_or_annual == "annual":
months_to_actually_remain_planted = min(plant_months_to_remain_planted, 12 - j)
for l in range(months_to_actually_remain_planted):
plants_growing_each_month_of_year[j + l].append(plants_planted_each_month_of_year[j][k])
for j in range(12):
planted_gardens_from_user[i].append(plants_growing_each_month_of_year[j])
for j in range(12):
for k in range(len(planted_gardens_from_user[i][j])):
all_plant_names_in_garden[i].append(planted_gardens_from_user[i][j][k]["plant_name"])
all_plant_names_in_garden[i] = list(set(all_plant_names_in_garden[i]))
total_different_plants_in_garden[i] = len(all_plant_names_in_garden[i])
garden_size = int(garden_ids_from_user[i]["garden_size_metres_squared"])
for j in range(12):
space_remaining_each_month[i][j] = garden_size
for j in range(12):
for k in range(len(planted_gardens_from_user[i][j])):
plant_space_required = float(planted_gardens_from_user[i][j][k]["metres_squared_required"]) * float(planted_gardens_from_user[i][j][k]["number_of_plants"])
space_remaining_each_month[i][j] -= plant_space_required
return render_template("index.html", space_remaining_each_month=space_remaining_each_month, all_plant_names_in_garden=all_plant_names_in_garden, total_different_plants_in_garden=total_different_plants_in_garden, garden_ids_from_user=garden_ids_from_user, planted_gardens_from_user=planted_gardens_from_user, number_of_gardens_from_user=number_of_gardens_from_user, admin_id=admin_id, username=username, months_of_year=months_of_year)
@app.route("/admin", methods=["GET", "POST"])
@login_required
def admin():
with db.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE username = %s", ('admin',))
admin = cur.fetchall()
admin_id = admin[0]["user_id"]
cur.execute("SELECT * FROM users WHERE user_id = %s", (session["user_id"],))
username = cur.fetchall()[0]["username"]
if len(admin) == 1 and session["user_id"] == admin_id:
if request.method == "POST":
# Insert new data from admin page into database
if request.form.get("add_plant_button"):
if not request.form.get("plant_name_add"):
return error("Must provide plant name.", 400)
elif not request.form.get("duration_to_maturity_months_add"):
return error("Must provide duration to maturity (months).", 400)
elif not request.form.get("plant_spacing_metres_add"):
return error("Must provide spacing (metres).", 400)
elif not request.form.get("metres_squared_required_add"):
return error("Must provide space required (metres squared).", 400)
elif not request.form.get("perennial_or_annual_add"):
return error("Must specify perennial or annual.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_add")) or not request.form.get("plant_name_add").islower():
return error("Plant name must be lowercase and alphabetical.", 400)
try:
duration_to_maturity_months_add = int(request.form.get("duration_to_maturity_months_add"))
except ValueError:
return error("Duration to maturity (months) must be integer.", 400)
if duration_to_maturity_months_add <= 0:
return error("Duration to maturity (months) must be positive number.", 400)
try:
plant_spacing_metres_add = int(request.form.get("plant_spacing_metres_add"))
except ValueError:
try:
plant_spacing_metres_add = float(request.form.get("plant_spacing_metres_add"))
except ValueError:
return error("Spacing (metres) must be integer or decimal number.", 400)
if plant_spacing_metres_add <= 0:
return error("Spacing (metres) must be positive number.", 400)
try:
metres_squared_required_add = int(request.form.get("metres_squared_required_add"))
except ValueError:
try:
metres_squared_required_add = float(request.form.get("metres_squared_required_add"))
except ValueError:
return error("Required space per plant (metres squared) must be integer or decimal number.", 400)
if metres_squared_required_add <= 0:
return error("Required space per plant (metres squared) must be positive number.", 400)
if request.form.get("perennial_or_annual_add") != "perennial" and request.form.get("perennial_or_annual_add") != "annual":
return error("Must select either perennial or annual.", 400)
january_add = "no"
february_add = "no"
march_add = "no"
april_add = "no"
may_add = "no"
june_add = "no"
july_add = "no"
august_add = "no"
september_add = "no"
october_add = "no"
november_add = "no"
december_add = "no"
if request.form.get("january_add") == "yes":
january_add = "yes"
if request.form.get("february_add") == "yes":
february_add = "yes"
if request.form.get("march_add") == "yes":
march_add = "yes"
if request.form.get("april_add") == "yes":
april_add = "yes"
if request.form.get("may_add") == "yes":
may_add = "yes"
if request.form.get("june_add") == "yes":
june_add = "yes"
if request.form.get("july_add") == "yes":
july_add = "yes"
if request.form.get("august_add") == "yes":
august_add = "yes"
if request.form.get("september_add") == "yes":
september_add = "yes"
if request.form.get("october_add") == "yes":
october_add = "yes"
if request.form.get("november_add") == "yes":
november_add = "yes"
if request.form.get("december_add") == "yes":
december_add = "yes"
cur.execute(
"INSERT INTO plants (plant_name, duration_to_maturity_months, plant_spacing_metres, metres_squared_required, perennial_or_annual, january, february, march, april, may, june, july, august, september, october, november, december) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
(
request.form.get("plant_name_add"),
duration_to_maturity_months_add,
plant_spacing_metres_add,
metres_squared_required_add,
request.form.get("perennial_or_annual_add"),
january_add,
february_add,
march_add,
april_add,
may_add,
june_add,
july_add,
august_add,
september_add,
october_add,
november_add,
december_add
)
)
db.commit()
return redirect("/admin")
if request.form.get("remove_plant_button"):
if not request.form.get("plant_name_remove"):
return error("Must provide plant name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_remove")) or not request.form.get("plant_name_remove").islower():
return error("Plant name must be lowercase and alphabetical.", 400)
cur.execute("SELECT plant_name FROM plants WHERE freetext = %s", ('no',))
plant_names = cur.fetchall()
cur.execute(
"""
SELECT plants.plant_name
FROM plants
INNER JOIN freetext_plants_users
ON plants.plant_id = freetext_plants_users.plant_id
WHERE plants.freetext = %s AND freetext_plants_users.user_id = %s
""",
('yes', int(session["user_id"]),)
)
freetext_plant_names_from_user = cur.fetchall()
is_plant_in_db = False
for i in range(len(plant_names)):
if plant_names[i]["plant_name"] == request.form.get("plant_name_remove"):
is_plant_in_db = True
for i in range(len(freetext_plant_names_from_user)):
if freetext_plant_names_from_user[i]["plant_name"] == request.form.get("plant_name_remove"):
is_plant_in_db = True
if is_plant_in_db == False:
return error("Plant name not found.", 400)
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_remove"),))
plant_id = cur.fetchone()
cur.execute("DELETE FROM plants WHERE plant_id = %s", (plant_id[0]["plant_id"],))
cur.execute("DELETE FROM planted_in_gardens WHERE plant_id = %s", (plant_id[0]["plant_id"],))
cur.execute("DELETE FROM companion_friends WHERE plant_id_a = %s OR plant_id_b = %s", (plant_id[0]["plant_id"], plant_id[0]["plant_id"]))
cur.execute("DELETE FROM companion_enemies WHERE plant_id_a = %s OR plant_id_b = %s", (plant_id[0]["plant_id"], plant_id[0]["plant_id"]))
db.commit()
return redirect("/admin")
if request.form.get("update_plant_button"):
if not request.form.get("plant_name_update"):
return error("Must provide plant name.", 400)
elif not request.form.get("duration_to_maturity_months_update"):
return error("Must provide duration to maturity (months).", 400)
elif not request.form.get("plant_spacing_metres_update"):
return error("Must provide spacing (metres).", 400)
elif not request.form.get("metres_squared_required_update"):
return error("Must provide space required (metres squared).", 400)
elif not request.form.get("perennial_or_annual_update"):
return error("Must specify perennial or annual.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_update")) or not request.form.get("plant_name_update").islower():
return error("Plant name must be lowercase and alphabetical.", 400)
plant_name = request.form.get("plant_name_update")
if request.form.get("new_plant_name_update"):
if not all(x.isalpha() or x.isspace() for x in request.form.get("new_plant_name_update")) or not request.form.get("new_plant_name_update").islower():
return error("New plant name must be lowercase and alphabetical.", 400)
plant_name = request.form.get("new_plant_name_update")
try:
duration_to_maturity_months_update = int(request.form.get("duration_to_maturity_months_update"))
except ValueError:
return error("Duration to maturity (months) must be integer.", 400)
if duration_to_maturity_months_update <= 0:
return error("Duration to maturity (months) must be positive number.", 400)
try:
plant_spacing_metres_update = int(request.form.get("plant_spacing_metres_update"))
except ValueError:
try:
plant_spacing_metres_update = float(request.form.get("plant_spacing_metres_update"))
except ValueError:
return error("Spacing (metres) must be integer or decimal number.", 400)
if plant_spacing_metres_update <= 0:
return error("Spacing (metres) must be positive number.", 400)
try:
metres_squared_required_update = int(request.form.get("metres_squared_required_update"))
except ValueError:
try:
metres_squared_required_update = float(request.form.get("metres_squared_required_update"))
except ValueError:
return error("Required space per plant (metres squared) must be integer or decimal number.", 400)
if metres_squared_required_update <= 0:
return error("Required space per plant (metres squared) must be positive number.", 400)
if request.form.get("perennial_or_annual_update") != "perennial" and request.form.get("perennial_or_annual_update") != "annual":
return error("Must select either perennial or annual.", 400)
january_update = "no"
february_update = "no"
march_update = "no"
april_update = "no"
may_update = "no"
june_update = "no"
july_update = "no"
august_update = "no"
september_update = "no"
october_update = "no"
november_update = "no"
december_update = "no"
if request.form.get("january_update") == "yes":
january_add = "yes"
if request.form.get("february_update") == "yes":
february_add = "yes"
if request.form.get("march_update") == "yes":
march_add = "yes"
if request.form.get("april_update") == "yes":
april_add = "yes"
if request.form.get("may_update") == "yes":
may_add = "yes"
if request.form.get("june_update") == "yes":
june_add = "yes"
if request.form.get("july_update") == "yes":
july_add = "yes"
if request.form.get("august_update") == "yes":
august_add = "yes"
if request.form.get("september_update") == "yes":
september_add = "yes"
if request.form.get("october_update") == "yes":
october_add = "yes"
if request.form.get("november_update") == "yes":
november_add = "yes"
if request.form.get("december_update") == "yes":
december_add = "yes"
cur.execute(
"UPDATE plants SET plant_name = %s, duration_to_maturity_months = %s, plant_spacing_metres = %s, metres_squared_required = %s, perennial_or_annual = %s, january = %s, february = %s, march = %s, april = %s, may = %s, june = %s, july = %s, august = %s, september = %s, october = %s, november = %s, december = %s WHERE plant_name = %s",
(
plant_name,
duration_to_maturity_months_update,
plant_spacing_metres_update,
metres_squared_required_update,
request.form.get("perennial_or_annual_update"),
january_update,
february_update,
march_update,
april_update,
may_update,
june_update,
july_update,
august_update,
september_update,
october_update,
november_update,
december_update,
request.form.get("plant_name_update"),
),
)
db.commit()
return redirect("/admin")
if request.form.get("add_companion_friends_button"):
if not request.form.get("plant_name_add_friend_a"):
return error("Must provide plant A name.", 400)
elif not request.form.get("plant_name_add_friend_b"):
return error("Must provide plant B name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_add_friend_a")) or not request.form.get("plant_name_add_friend_a").islower():
return error("Plant A name must be lowercase and alphabetical.", 400)
elif not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_add_friend_b")) or not request.form.get("plant_name_add_friend_b").islower():
return error("Plant B name must be lowercase and alphabetical.", 400)
cur.execute("SELECT plant_name FROM plants")
plant_names = cur.fetchall()
cur.execute("SELECT plant_name FROM freetext_plants WHERE user_id = %s", (int(session["user_id"]),))
freetext_plant_names_from_user = cur.fetchall()
is_plant_a_in_db = False
is_plant_b_in_db = False
for i in range(len(plant_names)):
if plant_names[i]["plant_name"] == request.form.get("plant_name_add_friend_a"):
is_plant_a_in_db = True
if plant_names[i]["plant_name"] == request.form.get("plant_name_add_friend_b"):
is_plant_b_in_db = True
for i in range(len(freetext_plant_names_from_user)):
if freetext_plant_names_from_user[i]["plant_name"] == request.form.get("plant_name_add_friend_a"):
is_plant_a_in_db = True
if freetext_plant_names_from_user[i]["plant_name"] == request.form.get("plant_name_add_friend_b"):
is_plant_b_in_db = True
if not is_plant_a_in_db:
return error("Plant A name not found. Consider adding as freetext before trying again.", 400)
if not is_plant_b_in_db:
return error("Plant B name not found. Consider adding as freetext before trying again.", 400)
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_add_friend_a"),))
plant_a_id = cur.fetchone()
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_add_friend_b"),))
plant_b_id = cur.fetchone()
cur.execute(
"INSERT INTO companion_friends (plant_id_a, plant_id_b) VALUES (%s, %s)",
(plant_a_id["plant_id"], plant_b_id["plant_id"])
)
db.commit()
return redirect("/admin")
if request.form.get("remove_companion_friends_button"):
if not request.form.get("plant_name_remove_friend_a"):
return error("Must provide plant A name.", 400)
elif not request.form.get("plant_name_remove_friend_b"):
return error("Must provide plant B name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_remove_friend_a")) or not request.form.get("plant_name_remove_friend_a").islower():
return error("Plant A name must be lowercase and alphabetical.", 400)
elif not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_remove_friend_b")) or not request.form.get("plant_name_remove_friend_b").islower():
return error("Plant B name must be lowercase and alphabetical.", 400)
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_remove_friend_a"),))
plant_a_id = cur.fetchone()
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_remove_friend_b"),))
plant_b_id = cur.fetchone()
cur.execute("SELECT * FROM companion_friends")
companion_friends = cur.fetchall()
are_plants_a_and_b_friends = False
for i in range(len(companion_friends)):
if companion_friends[i]["plant_id_a"] == plant_a_id[0]["plant_id"]:
if companion_friends[i]["plant_id_b"] == plant_b_id[0]["plant_id"]:
are_plants_a_and_b_friends = True
if companion_friends[i]["plant_id_b"] == plant_a_id[0]["plant_id"]:
if companion_friends[i]["plant_id_a"] == plant_b_id[0]["plant_id"]:
are_plants_a_and_b_friends = True
if not are_plants_a_and_b_friends:
return error("Plants A and B are not friends.", 400)
cur.execute("DELETE FROM companion_friends WHERE plant_id_a = %s AND plant_id_b = %s", (plant_a_id[0]["plant_id"], plant_b_id[0]["plant_id"]))
cur.execute("DELETE FROM companion_friends WHERE plant_id_a = %s AND plant_id_b = %s", (plant_b_id[0]["plant_id"], plant_a_id[0]["plant_id"]))
db.commit()
return redirect("/admin")
if request.form.get("add_companion_enemies_button"):
if not request.form.get("plant_name_add_enemy_a"):
return error("Must provide plant A name.", 400)
elif not request.form.get("plant_name_add_enemy_b"):
return error("Must provide plant B name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_add_enemy_a")) or not request.form.get("plant_name_add_enemy_a").islower():
return error("Plant A name must be lowercase and alphabetical.", 400)
elif not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_add_enemy_b")) or not request.form.get("plant_name_add_enemy_b").islower():
return error("Plant B name must be lowercase and alphabetical.", 400)
cur.execute("SELECT plant_name from plants")
plant_names = cur.fetchall()
cur.execute("SELECT plant_name FROM freetext_plants WHERE user_id = %s", (int(session["user_id"]),))
freetext_plant_names_from_user = cur.fetchall()
is_plant_a_in_db = False
is_plant_b_in_db = False
for i in range(len(plant_names)):
if plant_names[i]["plant_name"] == request.form.get("plant_name_add_enemy_a"):
is_plant_a_in_db = True
if plant_names[i]["plant_name"] == request.form.get("plant_name_add_enemy_b"):
is_plant_b_in_db = True
for i in range(len(freetext_plant_names_from_user)):
if freetext_plant_names_from_user[i]["plant_name"] == request.form.get("plant_name_add_enemy_a"):
is_plant_a_in_db = True
if freetext_plant_names_from_user[i]["plant_name"] == request.form.get("plant_name_add_enemy_b"):
is_plant_b_in_db = True
if not is_plant_a_in_db:
return error("Plant A name not found. Consider adding as freetext before trying again.", 400)
if not is_plant_b_in_db:
return error("Plant B name not found. Consider adding as freetext before trying again.", 400)
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_add_enemy_a"),))
plant_a_id = cur.fetchall()
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_add_enemy_b"),))
plant_b_id = cur.fetchall()
cur.execute("INSERT INTO companion_enemies (plant_id_a, plant_id_b) VALUES (%s, %s)", (plant_a_id[0]["plant_id"], plant_b_id[0]["plant_id"]))
db.commit()
return redirect("/admin")
if request.form.get("remove_companion_enemies_button"):
if not request.form.get("plant_name_remove_enemy_a"):
return error("Must provide plant A name.", 400)
elif not request.form.get("plant_name_remove_enemy_b"):
return error("Must provide plant B name.", 400)
if not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_remove_enemy_a")) or not request.form.get("plant_name_remove_enemy_a").islower():
return error("Plant A name must be lowercase and alphabetical.", 400)
elif not all(x.isalpha() or x.isspace() for x in request.form.get("plant_name_remove_enemy_b")) or not request.form.get("plant_name_remove_enemy_b").islower():
return error("Plant B name must be lowercase and alphabetical.", 400)
cur.execute("SELECT plant_id FROM plants WHERE plant_name = %s", (request.form.get("plant_name_remove_enemy_a"),))
plant_a_id = cur.fetchall()
cur.execute("SELECT plant_id FROM plants WHERE plant_name = ?", (request.form.get("plant_name_remove_enemy_b"),))
plant_b_id = cur.fetchall()
cur.execute("SELECT * FROM companion_enemies")
companion_enemies = cur.fetchall()
are_plants_a_and_b_enemies = False
for i in range(len(companion_friends)):
if companion_enemies[i]["plant_id_a"] == plant_a_id[0]["plant_id"]:
if companion_enemies[i]["plant_id_b"] == plant_b_id[0]["plant_id"]:
are_plants_a_and_b_friends = True
if companion_enemies[i]["plant_id_b"] == plant_a_id[0]["plant_id"]:
if companion_enemies[i]["plant_id_a"] == plant_b_id[0]["plant_id"]:
are_plants_a_and_b_enemies = True
if not are_plants_a_and_b_enemies:
return error("Plants A and B are not enemies.", 400)
cur.execute("DELETE FROM companion_enemies WHERE plant_id_a = ? AND plant_id_b = ?", (plant_a_id[0]["plant_id"], plant_b_id[0]["plant_id"]))
cur.execute("DELETE FROM companion_enemies WHERE plant_id_a = ? AND plant_id_b = ?", (plant_b_id[0]["plant_id"], plant_a_id[0]["plant_id"]))
db.commit()
return redirect("/admin")
else:
return render_template("admin.html", admin_id=admin_id, username=username)
else:
return error("You are not an admin.", 401)
@app.route("/change_password", methods=["GET", "POST"])
@login_required
def change_password():
with db.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE username = 'admin'")
admin = cur.fetchall()
admin_id = None
if len(admin) == 1:
admin_id = admin[0]["user_id"]
cur.execute("SELECT * FROM users WHERE user_id = %s", (session["user_id"],))
username = cur.fetchall()[0]["username"]
if request.method == "POST":
if not request.form.get("new_password"):
return error("Must provide new password.", 400)
elif not request.form.get("confirmation"):
return error("Must provide password confirmation.", 400)
if request.form.get("new_password") != request.form.get("confirmation"):
return error("Passwords must match.", 400)
hash_password = generate_password_hash(request.form.get("new_password"))
cur.execute("UPDATE users SET hash_password = %s WHERE username = %s", (hash_password, username))
db.commit()
return redirect("/")
else:
return render_template("change_password.html", admin_id=admin_id, username=username)
@app.route("/information")
@login_required
def information():
with db.cursor(cursor_factory = psycopg2.extras.RealDictCursor) as cur:
cur.execute("SELECT * FROM users WHERE username = 'admin'")
admin = cur.fetchall()
admin_id = admin[0]["user_id"]
cur.execute("SELECT * FROM users WHERE user_id = %s", (session["user_id"],))
username = cur.fetchall()[0]["username"]
cur.execute("SELECT plant_name, duration_to_maturity_months, plant_spacing_metres, metres_squared_required, perennial_or_annual, january, february, march, april, may, june, july, august, september, october, november, december FROM plants ORDER BY plant_name")
plants = cur.fetchall()
cur.execute("SELECT freetext_plants.plant_name, freetext_plants.duration_to_maturity_months, freetext_plants.plant_spacing_metres, freetext_plants.metres_squared_required, freetext_plants.perennial_or_annual, freetext_plants.january, freetext_plants.february, freetext_plants.march, freetext_plants.april, freetext_plants.may, freetext_plants.june, freetext_plants.july, freetext_plants.august, freetext_plants.september, freetext_plants.october, freetext_plants.november, freetext_plants.december FROM freetext_plants WHERE freetext_plants.user_id = %s ORDER BY freetext_plants.plant_name", (int(session["user_id"]),))
freetext_plants_from_user = cur.fetchall()
companion_friends = []
cur.execute("SELECT * FROM companion_friends")
companion_friends_ids = cur.fetchall()
if len(companion_friends_ids) != 0:
cur.execute("SELECT plants_friends_a.plant_name AS companion_friends_plant_a, plants_friends_b.plant_name AS companion_friends_plant_b FROM companion_friends INNER JOIN plants AS plants_friends_a ON companion_friends.plant_id_a = plants_friends_a.plant_id INNER JOIN plants AS plants_friends_b ON companion_friends.plant_id_b = plants_friends_b.plant_id")
companion_friends = cur.fetchall()
deleted_row_quantity = 0
original_range_for_i = len(companion_friends) - 1
deleted_rows = []