-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1882 lines (1438 loc) · 81.6 KB
/
main.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
"""Welcome to the Pet Food Calculator!"""
from calculate_food import CalculateFood
from cs50 import SQL
from flask import Flask, render_template, redirect, url_for, request, flash, session
from flask_bootstrap import Bootstrap
from forms import NewSignalment, GetWeight, ReproStatus, LoginForm, RegisterForm, WorkForm, FoodForm
from find_info import FindInfo
from helpers import clear_variable_list, login_required
import os
from nutrition_api import human_foods
from werkzeug.security import check_password_hash, generate_password_hash
# Configure application
app = Flask(__name__)
# Add in Bootstrap
Bootstrap(app)
# Load environmental variables
app.config['SECRET_KEY'] = os.environ.get('KEY')
# Configure CS50 Library to use SQLite database
db = SQL("sqlite:///pet_food_calculator.db")
# Register the blueprint for human foods
app.register_blueprint(human_foods)
@app.route("/")
def home():
"""Includes welcome and disclaimers along with login/register buttons"""
user_id = session.get("user_id")
if user_id:
user = db.execute(
"SELECT username FROM users WHERE id = :user_id",
user_id=session["user_id"]
)
username = user[0]["username"]
return render_template("index.html", user=username)
return render_template("index.html")
@app.route("/calculate_new_pet")
def new_pet_calc():
"""Redirects to the start of the form, while clearing session variables"""
session["previous_route"] = "new_pet"
# Clear variables (except user ID)
clear_variable_list()
return redirect(url_for('pet_info'))
@app.route("/recalculate_for_pet")
def recalculate_pet():
"""Redirects to the start of the form, while clearing session variables"""
session["previous_route"] = "recalculate"
# Clear variables (except user ID)
clear_variable_list()
return redirect(url_for('finished_reports'))
@app.route("/login", methods=["GET", "POST"])
def login():
"""Logs an existing user in"""
form = LoginForm()
# Checks if the user's data is validated
if form.validate_on_submit():
# Check username and hashed password against the database
user_lookup = db.execute(
"SELECT * FROM users WHERE username = ?", request.form.get("username")
)
if user_lookup == None:
flash("Username not found.")
return redirect(url_for('login'))
# Ensure username exists and password is correct
elif not check_password_hash(user_lookup[0]["password"],
request.form.get("password")):
flash("Invalid password.")
return redirect(url_for('login'))
else:
flash(f"Logged in as {request.form.get('username')}!")
# Remember which user has logged in
session["user_id"] = user_lookup[0]["id"]
return render_template("index.html")
return render_template("login.html", form=form)
@app.route("/register", methods=["GET", "POST"])
def register():
"""Registers a new user"""
form = RegisterForm()
if form.validate_on_submit():
# Check user against info in the database
find_user = db.execute(
"SELECT * FROM users WHERE username = ?", request.form.get("username")
)
# Check if username exists already in the database
if len(find_user) != 0:
flash("That username already taken.")
# Check if the user's password matches the password verification
elif request.form.get("password") != request.form.get("confirm_password"):
flash("Passwords must match.")
else:
# If all checks pass, hash password
hashed_password = generate_password_hash(request.form.get("password"), method='pbkdf2:sha256', salt_length=8)
# Insert new info into database
db.execute("INSERT INTO users (username, password) VALUES(?, ?)", request.form.get("username"), hashed_password)
user = db.execute("SELECT * FROM users WHERE username = ?", request.form.get("username"))
# Remember which user has logged in
session["user_id"] = user[0]["id"]
logged_in = True
# Redirect to home
return render_template("index.html", logged_in=logged_in)
return render_template("register.html", form=form)
@app.route("/logout")
def logout():
"""Logs user out"""
# Clears the user_id
session.clear()
# Redirect to home
return redirect("/")
@app.route("/get-signalment/", methods=["GET", "POST"])
@login_required
def pet_info():
"""Gets the pet's signalment, i.e. name, age, sex/reproductive status, breed, species"""
id = None
try:
pet_id = request.args.get("pet_id")
fi = FindInfo(session["user_id"], pet_id)
print(f"pet ID: {pet_id}")
except Exception as e:
print(f"Couldn't find ID, Exception: {e}")
else:
print(f"user_id: {session['user_id']}, pet_id: {id}")
form = NewSignalment()
if request.method == "POST":
fi = FindInfo(session["user_id"], pet_id)
species = form.pet_species.data
pet_name = form.pet_name.data.title()
id = fi.find_pet_id(session["user_id"], pet_name, species)
session["pet_id"] = id
print(id)
# Show an error message if the user doesn't choose a species
if species == "default":
flash("Please choose a species from the dropdown.")
return redirect(url_for("pet_info", pet_id=id))
if id != None:
print(f"user_id: {session['user_id']}, pet_id: {id}")
# See if the pet is already added
find_existing_pet = fi.find_existing_pet(session["user_id"], id)
print(find_existing_pet)
if find_existing_pet:
# If existing pet is found, update the data
print("Existing pet found")
try:
db.execute(
"UPDATE pets SET name = :updated_name, species = :updated_species \
WHERE pet_id = :pet_id AND owner_id = :user_id",
updated_name=pet_name, updated_species=species, pet_id=id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update data, Exception: {e}")
return redirect(url_for("pet_info", pet_id=id))
else:
session["species"] = species
session["pet_name"] = pet_name
session["pet_id"] = id
pet_id = id
else:
# If no pet is found (i.e. new pet in the database), create new session variables and store pet
print("New pet")
try:
# Insert new pet data
db.execute(
"INSERT INTO pets (owner_id, name, species) VALUES (?, ?, ?)",
session["user_id"], pet_name, species
)
print("Looking up new pet's ID")
# Query the new pet's id
pet_data = db.execute(
"SELECT pet_id, name FROM pets \
WHERE owner_id = :user_id AND name = :pet_name",
user_id=session["user_id"], pet_name=pet_name
)
print(pet_data[0]["pet_id"], pet_data[0]["name"])
new_pet_id = pet_data[0]["pet_id"]
except Exception as e:
flash(f"Unable to insert and query new signalment data, Exception: {e}")
return redirect(url_for("pet_info", pet_id=id))
else:
pet_id = new_pet_id
session["pet_id"] = pet_id
# Update the pet_data dictionary with the new pet's id
pet_data[0]["pet_id"] = pet_id
fi = FindInfo(session["user_id"], pet_id)
# Store session variables
session["species"] = species
session["pet_name"] = pet_name
fi = FindInfo(session["user_id"], pet_id)
print(pet_id, species, pet_name)
if pet_id is not None:
return redirect(url_for('pet_info_continued', pet_id=pet_id))
else:
flash("Pet ID is not available. Please try again.")
return redirect(url_for("pet_info", pet_id=id))
return render_template("get_signalment.html", form=form)
@app.route("/get-signalment-pt-2/<int:pet_id>", methods=["GET", "POST"])
@login_required
def pet_info_continued(pet_id):
"""Gets the rest of pet's signalment,
i.e. name, age, sex/reproductive status, breed, species"""
form = NewSignalment()
try:
print(f"pet ID: {pet_id}")
fi = FindInfo(session["user_id"], pet_id)
# Use login check from find_info to verify species
species = fi.login_check_for_species()
except Exception as e:
flash(f"Couldn't find ID, Exception: {e}")
return redirect(url_for('pet_info_continued', pet_id=pet_id))
else:
# AKC Breeds by Size csv courtesy of MeganSorenson of Github
# # # https://github.com/MeganSorenson/American-Kennel-Club-Breeds-by-Size-Dataset/blob/main/AmericanKennelClubBreedsBySize.xlsx
# Access breed data via database
pet_breed = []
if species == "Canine":
canine_breed_list = db.execute(
"SELECT Breed FROM dog_breeds ORDER BY Breed"
)
if canine_breed_list != None:
pet_breed += canine_breed_list
if species == "Feline":
feline_breed_list = db.execute(
"SELECT Breed FROM cat_breeds ORDER BY Breed"
)
if feline_breed_list != None:
pet_breed += feline_breed_list
if request.method == "POST":
pet_sex = form.pet_sex.data
pet_age_years = form.pet_age.data
pet_age_months = form.pet_age_months.data
pet_breed = request.form.get("pet_breed")
# Show an error message if the user doesn't choose a breed or sex
if pet_breed == None and pet_sex == "default":
flash("Please choose a breed and your pet's reproductive status from the dropdown menus.")
return redirect(url_for('pet_info_continued', pet_id=pet_id))
elif pet_breed == None and pet_sex != "default":
flash("Please choose a breed from the dropdown menus.")
return redirect(url_for('pet_info_continued', pet_id=pet_id))
elif pet_breed != None and pet_sex == "default":
flash("Please choose your pet's reproductive status from the dropdown menus.")
return redirect(url_for('pet_info_continued', pet_id=pet_id))
elif pet_age_years < 0 or pet_age_months < 0:
flash("Please enter 0 or a number greater than zero.")
return redirect(url_for('pet_info_continued', pet_id=pet_id))
else:
pet_sex = int(pet_sex)
print(pet_age_years, pet_age_months)
if pet_age_months > 12:
# If more than 12 months is input, add number to years
pet_age_years += pet_age_months / 12
# Get the integer part of pet_age_years
pet_age_years_int = int(pet_age_years)
# Get the decimal part of pet_age_years
pet_age_years_decimal = pet_age_years - pet_age_years_int
# Convert the decimal part of pet_age_years back to months
pet_age_months = round(pet_age_years_decimal * 12)
# Update pet_age_years to only include the integer part
pet_age_years = pet_age_years_int
print(pet_age_years, pet_age_months)
# Create new session variables
session["pet_sex"] = pet_sex
session["pet_age_years"] = pet_age_years
session["pet_age_months"] = pet_age_months
session["pet_breed"] = pet_breed
# Convert months to years for easier logic reading
partial_years = float(pet_age_months / 12)
pet_age = pet_age_years + partial_years
print(pet_age)
print(pet_sex, type(pet_sex))
# Set flags to see if a pet is between pediatric and sexually mature ages
is_pediatric = "n"
not_pediatric_not_mature = False
sexually_mature = False
# Search for pet breed code in breed database
if species == "Canine":
breed_id_result = db.execute(
"SELECT BreedID FROM dog_breeds WHERE Breed = ?", pet_breed
)
breed_id = breed_id_result[0]["BreedID"]
print(f"breed_id: {breed_id}")
# Find breed size category
breed_size_results = db.execute(
"SELECT SizeCategory FROM dog_breeds WHERE BreedID = ?;", breed_id
)
breed_size = breed_size_results[0]["SizeCategory"]
print(breed_size)
if breed_size == "X-Small" or breed_size == "Small" or breed_size == "Medium":
if pet_age < 0.33:
# Puppies under 4 months old have a DER modifier of * 3.0 factor_id 13
print("DER Modifier * 3.0")
der_factor_id = 13
is_pediatric = "y"
elif pet_age >= 0.33 and pet_age <= 0.66:
# Toy/small/medium breed puppies between 4 and 8 months of age have a DER modifier of * 2.5
print("DER Modifier * 2.5")
der_factor_id = 15
is_pediatric = "y"
elif pet_age > 0.66 and pet_age <= 1:
# Toy/small/medium breed puppies between 8 and 12 months of age have a DER modifier of * 1.8-2.0
print("DER Modifier * 1.8-2.0")
der_factor_id = 18
is_pediatric = "y"
elif pet_age > 1 and pet_age < 2:
# Toy/small/medium breed dogs that aren't pediatric but aren't sexually matue
not_pediatric_not_mature = True
else:
# Pets over 2 years old
sexually_mature = True
elif breed_size == "Large":
if pet_age < 0.33:
# Large breed puppies under 4 months old have a DER modifier of * 3.0 factor_id 13
print("DER Modifier * 3.0")
der_factor_id = 13
is_pediatric = "y"
elif pet_age > 0.33 and pet_age <= 0.91:
# Large breed puppies between 4 and 11 months old have a DER modifier of * 2.5
print("DER Modifier * 2.5")
der_factor_id = 16
is_pediatric = "y"
elif pet_age > 0.91 and pet_age <= 1.5:
# Large breed puppies between 11 and 18 months old have a DER modifier of * 1.8-2.0
print("DER Modifier * 1.8-2.0")
der_factor_id = 18
is_pediatric = "y"
elif pet_age > 1.5 and pet_age < 2:
# Large breed dogs that aren't pediatric but aren't sexually matue
not_pediatric_not_mature = True
else:
# Pets over 2 years old
sexually_mature = True
elif breed_size == "X-Large":
if pet_age < 0.33:
# X-Large breed puppies under 6 months old have a DER modifier of * 3.0 factor_id 13
der_factor_id = 13
print("DER Modifier * 3.0")
is_pediatric = "y"
if pet_age > 0.5 and pet_age <= 1:
# X-Large breed puppies between 6 and 12 months old have a DER modifier of * 2.5
print("DER Modifier * 2.5")
der_factor_id = 17
is_pediatric = "y"
elif pet_age > 1 and pet_age <= 1.5:
# X-Large breed puppies between 12 and 18 months old have a DER modifier of * 1.8-2.0
print("DER Modifier * 1.8-2.0")
der_factor_id = 20
is_pediatric = "y"
elif pet_age > 1.5 and pet_age < 2:
# X-Large breed dogs that aren't pediatric but aren't sexually matue
not_pediatric_not_mature = True
else:
# Pets over 2 years old
sexually_mature = True
# List for condensed conditionals suggested by CoPilot
if not_pediatric_not_mature or sexually_mature:
if pet_sex == 2 or pet_sex == 4:
# Non-pediatric, sexually immature and older dogs that are neutered or spayed
print("DER Modifier * 1.4-1.6")
der_factor_id = 1
elif pet_sex == 1 or pet_sex == 3:
# Non-pediatric, sexually immature or intact male dogs
print("DER Modifier * 1.6-1.8")
der_factor_id = 2
print(breed_size)
print(session["user_id"])
print(session["pet_name"])
print(breed_id, der_factor_id, pet_age_years, pet_age_months, pet_breed, pet_sex)
try:
db.execute(
"UPDATE pets SET canine_breed_id = :breed_id, canine_der_factor_id = :der_factor_id, \
age_in_years = :y, age_in_months = :m, breed = :breed, sex = :sex, is_pediatric = :pediatric_status \
WHERE pet_id = :pet_id AND owner_id = :user_id",
breed_id=breed_id, der_factor_id=der_factor_id, y=pet_age_years, m=pet_age_months, breed=pet_breed, \
sex=pet_sex, pediatric_status=is_pediatric, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update data. Exception: {e}")
return redirect(url_for("pet_info_continued", form=form, pet_id=pet_id))
if species == "Feline":
breed_id_result = db.execute(
"SELECT BreedID FROM cat_breeds WHERE Breed = ?", pet_breed
)
breed_id = breed_id_result[0]["BreedID"]
print(breed_id)
# DER factors suggested by https://todaysveterinarynurse.com/wp-content/uploads/sites/3/2018/07/TVN-2018-03_Puppy_Kitten_Nutrition.pdf
# and https://www.veterinary-practice.com/article/feeding-for-optimal-growth
if pet_age <= 0.33 or pet_age > 0.5 and pet_age <= 0.83:
# Kittens under 4 months old or between 7 and 10 months old have a DER modifier of * 2.0
print("DER Modifier * 2.0")
der_factor_id = 13
is_pediatric = "y"
elif pet_age > 0.33 and pet_age <= 0.5:
#Kittens between 5 and 6 months old have a DER modifier of * 2.5
print("DER Modifier * 2.5")
der_factor_id = 14
is_pediatric = "y"
elif pet_age > 0.83 and pet_age <= 1:
# Kittens between 10 and 12 months old have a DER modifier of * 1.8-2.0
print("DER Modifier * 1.8-2.0")
der_factor_id = 15
is_pediatric = "y"
elif pet_age > 1 and pet_age < 2:
# Kittens that aren't pediatric but aren't sexually matue
not_pediatric_not_mature = True
elif pet_age >= 2 and pet_age < 7:
# Pets over 2 years old
sexually_mature = True
elif pet_age >= 7 and pet_age <= 11:
# Cats between 7 and 11 years of age have a DER modifier of * 1.1-1.4
print("DER Modifier * 1.1-1.4")
der_factor_id = 4
elif pet_age >= 11:
# Cats older than 11 years have a DER modifier of * 1.1-1.6
print("DER Modifier * 1.1-1.6")
der_factor_id = 5
if not_pediatric_not_mature or sexually_mature:
if pet_sex == 2 or pet_sex == 4:
# Non-pediatric, sexually immature and older cats that are neutered or spayed
print("DER Modifier * 1.2-1.4")
der_factor_id = 1
elif pet_sex == 1 or pet_sex == 3:
# Non-pediatric, sexually immature or intact male cats
print("DER Modifier * 1.4-1.6")
der_factor_id = 2
print (der_factor_id)
try:
db.execute(
"UPDATE pets SET feline_breed_id = :breed_id, feline_der_factor_id = :der_factor_id, \
age_in_years = :y, age_in_months = :m, breed = :breed, sex = :sex, is_pediatric = :pediatric_status \
WHERE pet_id = :pet_id AND owner_id = :user_id",
breed_id=breed_id, der_factor_id=der_factor_id, y=pet_age_years, m=pet_age_months, breed=pet_breed, \
sex=pet_sex, pediatric_status=is_pediatric, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update part 2 of signalment data, Exception: {e}")
return redirect(url_for("pet_info_continued", form=form, pet_id=pet_id))
# Store new info as session variables
session["der_factor_id"] = der_factor_id
session["breed_id"] = breed_id
session["is_pediatric"] = is_pediatric
if pet_age >= 2 and pet_sex == 1:
# If the pet is a mature intact female, redirect to pregnancy questions
return redirect(url_for('repro_status', pet_id=pet_id))
else:
# redirect to pet body condition score questions
return redirect(url_for('pet_condition', pet_id=pet_id))
return render_template("get_signalment_part_2.html", form=form, pet_breed=pet_breed, species=species, pet_id=pet_id)
@app.route("/pregnancy_status/<int:pet_id>", methods=["GET", "POST"])
@login_required
def repro_status(pet_id):
"""Gets information about the pet's pregnancy status"""
repro = ReproStatus()
try:
print(f"pet ID: {pet_id}")
fi = FindInfo(session["user_id"], pet_id)
# Use login check from find_info to verify species
species = fi.login_check_for_species()
except Exception as e:
flash(f"Couldn't find ID, Exception: {e}")
return redirect(url_for('repro_status', pet_id=pet_id))
if request.method == "POST":
pregnancy_status = repro.pregnancy_status.data
# Store new info as session variables
session["pregnancy_status"] = pregnancy_status
print(pregnancy_status)
try:
db.execute(
"UPDATE pets SET is_pregnant = :is_pregnant WHERE pet_id = :pet_id AND owner_id = :user_id",
is_pregnant=pregnancy_status, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to insert pregnancy data, Exception: {e}")
return redirect(url_for("repro_status", pet_id=pet_id))
if pregnancy_status == "y":
if species == "Canine":
# If pet is pregnant and canine, ask how many weeks along she is
return redirect(url_for('gestation_duration', pet_id=pet_id))
else:
# If pet is pregnant and feline, DER factor is * 1.6-2.0
der_factor_id = 7
print (der_factor_id)
try:
db.execute(
"UPDATE pets SET feline_der_factor_id = :der_factor_id WHERE pet_id = :pet_id AND owner_id = :user_id",
der_factor_id=der_factor_id, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update feline DER factor id for gestation data, Exception: {e}")
return redirect(url_for("repro_status", repro=repro, pet_id=pet_id))
# Update session variable
session["der_factor_id"] = der_factor_id
return redirect(url_for('pet_condition', species=species, pet_id=pet_id))
else:
# If pet is not pregnant, ask if she is currently nursing a litter
return redirect(url_for('lactation_status', pet_id=pet_id))
return render_template("get_reproductive_status.html", repro=repro, pet_id=pet_id)
@app.route("/gestation_duration/<int:pet_id>", methods=["GET", "POST"])
@login_required
def gestation_duration(pet_id):
"""Asks for how long the pet has been pregnant for if they are canine
and assigns DER factor"""
repro = ReproStatus()
# Use login check from find_info to verify species
fi = FindInfo(session["user_id"], pet_id)
species = fi.login_check_for_species()
if request.method == "POST":
number_weeks_pregnant = repro.weeks_gestation.data
# Use check from find_info to verify DER factor id
der_factor_id = fi.der_factor()
# print(der_factor_id)
if number_weeks_pregnant <= "6":
# If pet is pregnant, canine, and within the first 42 days of pregnancy, DER modifier is *~1.8
if der_factor_id != 5:
der_factor_id = 5
else:
# If pet is pregnant, canine, and within the last 21 days of pregnancy, DER modifier is *3
if der_factor_id != 6:
der_factor_id = 6
print(der_factor_id)
try:
db.execute(
"UPDATE pets SET weeks_gestating = :weeks_gestating, canine_der_factor_id = :der_factor_id WHERE pet_id = :pet_id AND owner_id = :user_id",
weeks_gestating=number_weeks_pregnant, der_factor_id=der_factor_id, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update data for gestation length, Exception: {e}")
return redirect(url_for("gestation_duration", pet_id=pet_id))
# Store new info as session variables
session["number_weeks_pregnant"] = number_weeks_pregnant
# Update DER factor ID variable
session["der_factor_id"] = der_factor_id
return redirect(url_for('pet_condition', pet_id=pet_id))
return render_template("gestation_duration.html", repro=repro, pet_id=pet_id)
@app.route("/litter_size/<int:pet_id>", methods=["GET", "POST"])
@login_required
def litter_size(pet_id):
"""Asks for the litter size of pets that have one, then assigns DER modifier"""
repro = ReproStatus()
# Use login check from find_info to verify species
fi = FindInfo(session["user_id"], pet_id)
species = fi.login_check_for_species()
if request.method == "POST":
litter_size = repro.litter_size.data
# Stores litter size data in the session
session["litter_size"] = litter_size
try:
db.execute(
"UPDATE pets SET litter_size = :size WHERE pet_id = :pet_id AND owner_id = :user_id",
size=litter_size, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update litter size, Exception: {e}")
return redirect(url_for("litter_size", pet_id=pet_id))
# Use find_info to check DER factor ID
der_factor_id = fi.der_factor()
if species == "Feline":
# If the pet is a nursing feline, ask for weeks of lactation
return redirect(url_for('lactation_duration', pet_id=pet_id))
elif species == "Canine":
# If pet is a nursing canine, DER modifier changes based on litter size
if litter_size == 1:
# 1 puppy: * 3.0
der_factor_id = 7
elif litter_size == 2:
# 2 puppies: 3.5
der_factor_id = 8
elif litter_size == 3 or litter_size == 4:
# 3-4 puppies: 4.0
der_factor_id = 9
elif litter_size == 5 or litter_size == 6:
# 5-6 puppies: 5.0
der_factor_id = 10
elif litter_size == 7 or litter_size == 8:
# 7-8 puppies: 5.5
der_factor_id = 11
elif litter_size >= 9:
# 9+ puppies >= 6.0
der_factor_id = 12
try:
db.execute(
"UPDATE pets SET canine_der_factor_id = :der_factor_id WHERE pet_id = :pet_id AND owner_id = :user_id",
der_factor_id=der_factor_id, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update canine DER factor ID for litter size, Exception: {e}")
return redirect(url_for("litter_size", pet_id=pet_id))
# Update DER factor ID variable
session["der_factor_id"] = der_factor_id
return redirect(url_for('pet_condition', pet_id=pet_id))
return render_template("get_litter_size.html", repro=repro, pet_id=pet_id)
@app.route("/lactation_status/<int:pet_id>", methods=["GET", "POST"])
@login_required
def lactation_status(pet_id):
"""Asks if the pet is currently nursing"""
repro = ReproStatus()
# Use login check from find_info to verify species
fi = FindInfo(session["user_id"], pet_id)
species = fi.login_check_for_species()
if request.method == "POST":
lactation_status = repro.nursing_status.data
# Stores lactation status variable in session
session["lactation_status"] = lactation_status
print(lactation_status)
# Add pet to the database if the user is logged in
try:
db.execute(
"UPDATE pets SET is_nursing = :lactation_status WHERE pet_id = :pet_id AND owner_id = :user_id",
lactation_status=lactation_status, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update lactation status data, Exception: {e}")
return redirect(url_for("lactation_status", pet_id=pet_id))
if lactation_status == "y":
# If pet is lactating, ask for litter size
return redirect(url_for('litter_size', pet_id=pet_id))
else:
# If pet is not lactating, next page is get_weight
return redirect(url_for('pet_condition', pet_id=pet_id))
return render_template("get_lactation_status.html", repro=repro, pet_id=pet_id)
@app.route("/lactation_duration/<int:pet_id>", methods=["GET", "POST"])
@login_required
def lactation_duration(pet_id):
"""Asks how many weeks a pregnant queen has been nursing and adds DER modifier"""
repro = ReproStatus()
# Use login check from find_info to verify species
fi = FindInfo(session["user_id"], pet_id)
species = fi.login_check_for_species()
if request.method == "POST":
duration_of_nursing = int(repro.weeks_nursing.data)
if duration_of_nursing <= 2:
# If the queen has been nursing for 2 weeks or less, DER modifier is RER + 30% per kitten
der_factor_id = 8
elif duration_of_nursing == 3:
# If the queen has been nursing for 3 weeks, DER modifier is RER + 45% per kitten
der_factor_id = 9
elif duration_of_nursing == 4:
# If the queen has been nursing for 4 weeks, DER modifier is RER + 55% per kitten
der_factor_id = 10
elif duration_of_nursing == 5:
# If the queen has been nursing for 5 weeks, DER modifier is RER + 65% per kitten
der_factor_id = 11
elif duration_of_nursing == 6:
# If the queen has been nursing for 6 weeks, DER modifier is RER + 90% per kitten
der_factor_id = 12
try:
db.execute(
"UPDATE pets SET weeks_nursing = :duration_of_nursing, feline_der_factor_id = :der_factor_id WHERE pet_id = :pet_id AND owner_id = :user_id",
duration_of_nursing=duration_of_nursing, der_factor_id=der_factor_id, pet_id=pet_id, user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update nursing timeframe data, Exception: {e}")
return redirect(url_for('lactation_duration', pet_id=pet_id))
# Stores nursing duration variable in session
session["duration_of_nursing"] = duration_of_nursing
# Update session variable
session["der_factor_id"] = der_factor_id
return redirect(url_for('pet_condition', pet_id=pet_id))
return render_template("lactation_duration.html", repro=repro, pet_id=pet_id)
@app.route("/get-weight/<int:pet_id>", methods=["GET", "POST"])
@login_required
def pet_condition(pet_id):
"""Gets the pet's weight and body condition score"""
form = GetWeight()
fi = FindInfo(session["user_id"], pet_id)
species = fi.login_check_for_species()
print(f"user_id: {session['user_id']}, pet_id: {id}")
# Use login check from find_info to verify species
species = fi.login_check_for_species()
if request.method == "POST":
bcs = int(form.pet_bcs.data)
weight = float(form.pet_weight.data)
units = form.pet_units.data
if units == "lbs":
# Convert weight to kilograms
converted_weight = round((weight / 2.2), 2)
converted_weight_units = "kgs"
elif units == "kgs":
# Convert weight to lbs
converted_weight = round((weight * 2.2), 2)
converted_weight_units = "lbs"
# print(bcs)
# print(type(bcs))
# print(weight)
# print(type(weight))
# print(units)
# print(type(units))
# Use find_info to verify DER factor ID
der_factor_id = fi.der_factor()
# check_litter_size()
print(f"Weight: {weight}{units}")
if bcs != 5:
# Calculate ideal weight
weight_proportion = round((100 / (((bcs - 5) * 10) + 100)), 3)
# print(f"weight_proportion: {weight_proportion}")
if units == "lbs":
est_ideal_weight_lbs = round((weight_proportion * weight), 2)
print(est_ideal_weight_lbs)
# Calculate ideal weight in kgs
est_ideal_weight_kgs = round((est_ideal_weight_lbs / 2.2), 2)
print(est_ideal_weight_kgs)
elif units == "kgs":
est_ideal_weight_kgs = round((weight_proportion * weight), 2)
print(est_ideal_weight_kgs)
# Calculate ideal weight in lbs
est_ideal_weight_lbs = round((est_ideal_weight_kgs * 2.2), 2)
print(est_ideal_weight_lbs)
else:
# If pet has 5/9 on the BCS scale, set estimated ideal weight as current weight
if units == "lbs":
est_ideal_weight_lbs = weight
est_ideal_weight_kgs = round((est_ideal_weight_lbs / 2.2), 2)
elif units == "kgs":
est_ideal_weight_kgs = weight
est_ideal_weight_lbs = round((est_ideal_weight_kgs * 2.2), 2)
# Store new info as session variables
session["bcs"] = bcs
session["weight"] = weight
session["units"] = units
session["converted_weight"] = converted_weight
session["converted_weight_units"] = converted_weight_units
session["ideal_weight_kgs"] = est_ideal_weight_kgs
session["ideal_weight_lbs"] = est_ideal_weight_lbs
bcs_to_body_fat = {1: "< 5", 2: "5", 3: "10", 4: "15", 5: "20",
6: "25", 7: "30", 8: "35", 9: ">=40"
}
# Find body fat percentage
percent_body_fat = bcs_to_body_fat[bcs]
print(percent_body_fat)
print(f"Estimated ideal weight: {est_ideal_weight_kgs} kgs, {est_ideal_weight_lbs} lbs")
# Check for pregnancy status and nursing status
pregnancy_status = fi.check_if_pregnant()
is_nursing = fi.check_if_nursing()
is_pediatric = fi.check_if_pediatric()
if species == "Canine":
if pregnancy_status != "y" and is_nursing != "y" and is_pediatric != "y":
# Only update DER factor id if pet isn't nursing or pregnant
if bcs <= 4:
# Change DER factor id to weight gain
der_factor_id = 24
elif bcs == 6:
# Change DER factor to weight loss
der_factor_id = 4
elif bcs > 6:
# Change DER factor to obese prone
der_factor_id = 3
# Check if pet breed is predisposed to obesity
obese_prone_breed = fi.check_obesity_risk()
print(obese_prone_breed)
if obese_prone_breed == "y" and pregnancy_status != "y" and is_nursing != "y" and is_pediatric != "y":
der_factor_id = 3
try:
print(session["pet_name"])
print(session["user_id"])
db.execute(
"UPDATE pets SET canine_der_factor_id = :der_factor_id, bcs = :body_condition_score, \
ideal_weight_lbs = :ideal_weight_lbs, ideal_weight_kgs = :ideal_weight_kgs, weight = :weight, \
units = :units, converted_weight = :converted_weight, converted_weight_units = :converted_weight_units, \
body_fat_percentage = :percent_body_fat WHERE pet_id = :pet_id AND owner_id = :user_id",
der_factor_id=der_factor_id, body_condition_score=bcs, ideal_weight_lbs=est_ideal_weight_lbs,
ideal_weight_kgs=est_ideal_weight_kgs, weight=weight, units=units, converted_weight=converted_weight,
converted_weight_units=converted_weight_units, percent_body_fat=percent_body_fat, pet_id=pet_id,
user_id=session["user_id"]
)
except Exception as e:
flash(f"Unable to update canine BCS data, Exception: {e}")
return render_template("get_weight_and_bcs.html", form=form)
# Update DER factor ID variable
session["der_factor_id"] = der_factor_id
# Gets a dog's activity level if applicable
return redirect(url_for('activity', pet_id=pet_id))