-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1239 lines (1061 loc) · 37.4 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 json
import secrets
import subprocess
from loguru import logger
from swapprfunctions import *
from datetime import datetime
from argparser import argparser
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from werkzeug.security import generate_password_hash
from flask import Flask, render_template, request, session, redirect, url_for, flash, jsonify
# Declare constant variables for search results; used in search route
MATCHING_SCORES = {
'HIGH_MATCHING_SCORE_MIN': 31,
'MEDIUM_MATCHING_SCORE_MAX': 30,
'MEDIUM_MATCHING_SCORE_MIN': 21,
'LOW_MATCHING_SCORE_MAX': 20,
'LOW_MATCHING_SCORE_MIN': 16
}
# Initialize basic functionalities
try:
# |----- BASIC FUNCTIONALITIES INITIALIZATION -----|
# Configure loguru for history log files
logger.remove(0)
initialize_logger()
# Flask instance to initialize the web application.
app = Flask(__name__)
# Declare a secret key for Flask application; needed for Flask flash
app.secret_key = secrets.token_hex(32)
# Initialize the database and tables
create_database_tables()
# Initialize Flask limiter instance for spam request protection
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["2000 per day", "500 per hour"],
storage_uri="memory://"
)
# |----- ARGPARSER FUNCTIONALITIES -----|
# Declare constant variables for POST request limits if limiter gets called
if argparser.limiter:
SIGNUP_LIMIT = "60/minute"
SIGNIN_LIMIT = "60/minute"
SUBMIT_LIMIT = "30/minute"
UPDATE_EXPOSURE_LIMIT = "30/minute"
EDIT_SUBMISSION_LIMIT = "60/minute"
SEARCH_LIMIT = "100/minute"
PASSWORD_RESET_LIMIT = "30/minute"
UPDATE_USERNAME_LIMIT = "30/minute"
DELETE_ACCOUNT_LIMIT = "30/minute"
# Run system file backup script - back ups database and logs
if argparser.backup:
logger.remove()
subprocess.run(['bash', 'fbak.sh'])
initialize_logger()
# Delete database and create/load mockup users and submissions for random testing
if argparser.mockupsgen and not argparser.premademockups:
insert_mockups(*argparser.mockupsgen)
# Delete database and load premade mockup users and submissions for solid testing
if argparser.premademockups and not argparser.mockupsgen:
insert_mockups()
# |----- LOCATION UPDATE FUNCTIONALITIES -----|
# Import location data from locations.json file into proper database tables
locations_update, new_locations_flag = import_locations()
# Inform log in case of newly imported locations in the database
log_new_locations(locations_update, new_locations_flag)
except Exception as err:
log(f'Unexpected {err=}, {type(err)=}')
raise
# ||||| ----- FLASK ROUTES ----- |||||
# |----- INDEX HTML ROUTE ----|
@app.route('/')
@login_required
def index():
# Get user data
user_id = session['user_id']
# Fetch all submissions for the logged user
query = '''
SELECT * FROM submissions
WHERE user_id = ?;
'''
submissions_data = cursor_fetch(query, user_id)
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: NAVIGATION: @index.html
'''
)
return render_template(
'index.html',
submissions=submissions_data,
comma=comma,
whitespace=whitespace
)
# |----- UPDATE EXPOSURE POST BUTTON ROUTE ----|
@app.route('/update_exposure', methods=['POST'])
@limiter.limit(f"{UPDATE_EXPOSURE_LIMIT}" if argparser.limiter else None)
@login_required
def update_exposure():
# Get user data
user_id = session['user_id']
# Retrieve data from the form
submission_id = request.form.get('submission_id')
new_exposure = request.form.get('new_exposure')
# Update exposure value in the database
query = '''
UPDATE submissions
SET exposure = ?
WHERE id = ?
AND user_id = ?;
'''
cursor_execute(
query,
new_exposure,
submission_id,
user_id
)
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: SUCCESS: Submission id {submission_id} changed exposure -> '{new_exposure}'
'''
)
# Inform user for successful exposure update
message = 'Exposure updated successfully!'
return jsonify({'success': message})
# |----- SIGN IN HTML AND POST BUTTON ROUTE ----|
@app.route('/signup', methods=['GET', 'POST'])
@limiter.limit(f"{SIGNUP_LIMIT}" if argparser.limiter else None)
def signup():
if request.method == 'POST':
# Get user submitted form data
email = request.form.get('email').lower()
username = request.form.get('username').lower()
password = request.form.get('password')
confirm_password = request.form.get('confirmPassword')
# Check if all form fields are filled and valid
try:
# Ensure user form input for signup is valid
signup_validation(
email,
username,
password,
confirm_password
)
# Hash password before storing it
hashed_password = generate_password_hash(
password,
method='scrypt',
salt_length=16
)
registration_date = datetime.now()
# Sign up new user
query = '''
INSERT INTO users (
email,
username,
hash,
registration_date,
verified_account
)
VALUES (?, ?, ?, ?, ?);
'''
cursor_execute(
query,
email,
username,
hashed_password,
registration_date,
False
)
# Update log with INFO msg
log(
f'''
{request.remote_addr}
SUCCESS: New user 'registered'
'email': {email}
'username': {username}
''',
indent=20
)
# Sign in new user
signin()
# Inform user for successful register
message = {
'success': 'Successfully registered!'
}
flash(message)
return redirect(url_for('delayed_redirect'))
except ValueError as err:
# Update log with ERROR msg
log(
f'''
[{request.remote_addr}]
USER[unregistered]: FAILED: Sign up: {err}
''',
level='WARNING',
indent=24
)
return render_template('/signup.html', error=err)
# Update log with INFO msg
log(
f'''
{request.remote_addr}
USER[unregistered]: NAVIGATION: @signup.html
'''
)
return render_template('/signup.html')
# |----- DELAYED REDIRECT HTML ROUTE ----|
@app.route('/delayed_redirect')
def delayed_redirect():
registration_timestamp = session.get('registration_timestamp')
# Check if the registration timestamp is set
if registration_timestamp:
# Calculate the time elapsed since registration
elapsed_time = datetime.now() - registration_timestamp
# If more than 4 seconds have passed, redirect to the home page
if elapsed_time >= 4:
return redirect('/')
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: Redirection @index.html
'''
)
return render_template('delayed_redirect.html')
# |----- SIGNIN HTML AND POST BUTTON ROUTE ----|
@app.route("/signin", methods=['GET', 'POST'])
@limiter.limit(f"{SIGNIN_LIMIT}" if argparser.limiter else None)
def signin():
# Forget any user_id
session.clear()
if request.method == 'POST':
# Get user submitted form data
username = request.form.get('username').lower()
password = request.form.get('password')
# Fetch user registered data
query = '''
SELECT * FROM users
WHERE username = ?;
'''
user_data = cursor_fetch(query, username)
# Check if all form fields are filled and valid
try:
# Ensure user form input for signin is valid
signin_validation(
username,
password,
user_data
)
# Store in session dictionary user details to be used later
session['user_id'] = user_data[0]['id']
session['username'] = user_data[0]['username']
session['email'] = user_data[0]['email']
session['ip'] = request.remote_addr
session['logged_user'] = {
'user_id': session['user_id'],
'email': session['email'],
'username': session['username'],
}
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: Signed in
''',
indent=20
)
# Redirect user to home page
return redirect('/')
except ValueError as err:
# Update log with ERROR msg
log(
f'''
{request.remote_addr}
USER[{'unregistered'}]: FAILED: Signin: {err}
''',
indent=20
)
return render_template('/signin.html', error=err)
# Update log with INFO msg
log(
f'''
{request.remote_addr}
USER[unregistered]: NAVIGATION: @signin.html
'''
)
return render_template('/signin.html')
# |----- SIGNOUT ROUTE ----|
@app.route('/signout')
@login_required
def signout():
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: Signed out
'''
)
# Forget any user_id
session.clear()
return redirect('/')
# |----- SUBMIT HTML AND POST BUTTON ROUTE ----|
@app.route('/submit', methods=['GET', 'POST'])
@limiter.limit(f"{SUBMIT_LIMIT}" if argparser.limiter else None)
@login_required
def submit():
# Fetch cities for the initial rendering of the form
cities = cursor_fetch('SELECT DISTINCT city FROM cities')
# Get user data
user_id = session['user_id']
if request.method == 'POST':
# Get user submitted form data
exposure = request.form.get('exposure')
house_type = request.form.get('houseType')
square_meters = request.form.get('squareMeters')
rental = request.form.get('rental')
bedrooms = request.form.get('bedrooms')
bathrooms = request.form.get('bathrooms')
city = request.form.get('city')
municipality = request.form.get('municipality')
region = request.form.get('region')
city_destination = request.form.get('cityDestination')
municipality_destination = request.form.get('municipalityDestination')
region_destination = request.form.get('regionDestination')
primary_submission = request.form.get('primarySubmission')
primary_submission_locked = request.form.get('primarySubmissionLocked')
all_field_values = list(request.form.values())
# Check if all form fields are filled and valid
try:
# Ensure user form input for submission is valid
submission_validation(
all_field_values,
exposure,
house_type,
square_meters,
rental,
bedrooms,
bathrooms,
city,
municipality,
region,
city_destination,
municipality_destination,
region_destination
# TODO add primary_submission (and locked) validation
)
# Update log with WARNING msg
log(
f'''
{session['ip']}
USER[{session['username']}]: SUCCESS: Submission 'validated'
''',
level='SUCCESS',
indent=20
)
# Determine True or False for primary_submission status
primary_submission = determine_primary_submission_status(
primary_submission,
primary_submission_locked,
user_id
)
# Save submission into user database
query = '''
INSERT INTO submissions (
user_id,
house_type,
square_meters,
rental,
bedrooms,
bathrooms,
city,
municipality,
region,
city_destination,
municipality_destination,
region_destination,
exposure,
primary_submission
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
'''
cursor_execute(
query,
user_id,
house_type,
square_meters,
rental,
bedrooms,
bathrooms,
city,
municipality,
region,
city_destination,
municipality_destination,
region_destination,
exposure,
primary_submission
)
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: SUCCESS: Submission 'saved'
''',
level='SUCCESS',
indent=20
)
# Inform user for successful submission
message = {
'success': 'Submission saved successfully!'
}
flash(message)
return redirect('/')
except ValueError as err:
# Update log with ERROR msg
log(
f'''
{session['ip']}
USER[{session['username']}]: FAILED: Submission 'aborted': {err}
''',
level='WARNING',
indent=20
)
return render_template(
'/submit.html',
submission=None,
error=err
)
else:
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: NAVIGATION: @submit.html
''',
indent=24
)
return render_template(
'/submit.html',
cities=cities,
submission=None,
user_submissions_exist=user_submissions_exist(user_id),
whitespace=whitespace
)
# |----- EDIT SUBMISSION HTML AND POST BUTTON ROUTE ----|
@app.route('/edit_submission', methods=['POST'])
@limiter.limit(f"{EDIT_SUBMISSION_LIMIT}" if argparser.limiter else None)
@login_required
def edit_submission():
# Fetch cities for the initial rendering of the form
cities = cursor_fetch('SELECT DISTINCT city FROM cities')
# Get user data
user_id = session['user_id']
# Retrieve data from the form
submission_id = request.form.get('submission_id')
try:
# Ensure submission existance
query = '''
SELECT * FROM submissions
WHERE id = ?
AND user_id = ?;
'''
submission_data = cursor_fetch(query, submission_id, user_id)
# If submission exists pass its data to the edit page, else reload index route
if submission_data:
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: NAVIGATION: @edit_submission.html
USER[{session['username']}]: SUCCESS: Submission id {submission_id} 'edit'
''',
indent=20
)
return render_template(
'/edit_submission.html',
cities=cities,
submission=submission_data[0],
user_submissions_exist=user_submissions_exist(user_id),
whitespace=whitespace,
)
except Exception as err:
# Update log with ERROR msg
log(
f'''
{session['ip']}
USER[{session['username']}]: FAILED: Submission id {submission_id} 'not found': {err}
''',
level='WARNING',
indent=24
)
# Inform user for submission search error
message = {
'error': 'Submission not found.'
}
flash(message)
return redirect(url_for('index'))
# |----- EDITED SUBMISSION SAVE AND DELETE POST BUTTON ROUTE ----|
@app.route('/edited_submission', methods=['POST'])
@limiter.limit(f"{EDIT_SUBMISSION_LIMIT}" if argparser.limiter else None)
@login_required
def save_edit_submission():
# Fetch cities for the initial rendering of the form
cities = cursor_fetch('SELECT DISTINCT city FROM cities')
# Get user data
user_id = session['user_id']
# Retrieve data from the form
submission_id = request.form.get('submission_id')
house_type = request.form.get('houseType')
square_meters = request.form.get('squareMeters')
rental = request.form.get('rental')
bedrooms = request.form.get('bedrooms')
bathrooms = request.form.get('bathrooms')
exposure = request.form.get('exposure')
city = request.form.get('city')
municipality = request.form.get('municipality')
region = request.form.get('region')
city_destination = request.form.get('cityDestination')
municipality_destination = request.form.get('municipalityDestination')
region_destination = request.form.get('regionDestination')
primary_submission = request.form.get('primarySubmission')
primary_submission_locked = request.form.get('primarySubmissionLocked')
all_field_values = list(request.form.values())
# Save edited house or delete it
if 'save' in request.form:
# Check if all form fields are filled and valid
try:
# Ensure user form input for edit submission is valid
submission_validation(
all_field_values,
exposure,
house_type,
square_meters,
rental,
bedrooms,
bathrooms,
city,
municipality,
region,
city_destination,
municipality_destination,
region_destination
# TODO add primary_su
# TODO add primary submission (and locked) validation
)
# Update log with WARNING msg
log(
f'''
{session['ip']}
USER[{session['username']}]: SUCCESS: Edited submission {submission_id} 'validated'
''',
level='WARNING',
indent=20
)
# Determine True or False for primary_submission status
primary_submission = determine_primary_submission_status(
primary_submission,
primary_submission_locked,
user_id
)
# Update edited submission into user database
query = '''
UPDATE submissions SET
house_type = ?,
square_meters = ?,
rental = ?,
bedrooms = ?,
bathrooms = ?,
city = ?,
municipality = ?,
region = ?,
city_destination = ?,
municipality_destination = ?,
region_destination = ?,
exposure = ?,
primary_submission = ?
WHERE id = ?
AND user_id = ?;
'''
cursor_execute(
query,
house_type,
square_meters,
rental,
bedrooms,
bathrooms,
city,
municipality,
region,
city_destination,
municipality_destination,
region_destination,
exposure,
primary_submission,
submission_id,
user_id
)
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: SUCCESS: Sumbission {submission_id} 'updated'
''',
indent=20
)
# Inform user for successful submission update
message = {
'success': 'Submission updated successfully!'
}
flash(message)
return redirect(url_for('index'))
except ValueError as err:
# Update log with ERROR msg
log(
f'''
{session['ip']}
USER[{session['username']}]: FAILED: Submission update 'aborted': {err}
''',
level='WARNING',
indent=20
)
# Fetch edited submission data to reload route with correct field values
query = '''
SELECT * FROM submissions
WHERE id = ?
AND user_id = ?;
'''
submission_data = cursor_fetch(query, submission_id, user_id)
return render_template(
'/edit_submission.html',
cities=cities,
submission=submission_data[0],
error=err,
whitespace=whitespace,
)
if 'delete' in request.form:
# If submission to be deleted needs special handling due to primary
# submission issues let the function do the job; else delete it instantly
if not handle_primary_submission_upon_deletion(
submission_id,
user_id,
):
# Delete edited submission from database
query = '''
DELETE FROM submissions
WHERE id = ?
AND user_id = ?;
'''
cursor_execute(
query,
submission_id,
user_id
)
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: SUCCESS: Submission {submission_id} 'deleted'
''',
indent=24
)
# Inform user for successful submission deletion
message = {
'success': 'Submission deleted successfully!'
}
flash(message)
return redirect(url_for('index'))
# |----- GET MUNICIPALITIES SELECT INPUT ROUTE ----|
@app.route('/get_municipalities')
def get_municipalities():
city = request.args.get('city')
query = '''
SELECT id FROM cities
WHERE city = ?;
'''
city_data = cursor_fetch(query, city)
city_id = city_data[0]['id']
# Fetch municipalities from the database based on the selected city
query = '''
SELECT municipality FROM municipalities
WHERE city_id = ?;
'''
municipalities = cursor_fetch(query, city_id)
return municipalities
# |----- GET REGIONS SELECT INPUT ROUTE ----|
@app.route('/get_regions')
def get_regions():
municipality = request.args.get('municipality')
query = '''
SELECT id FROM municipalities
WHERE municipality = ?;
'''
municipality_data = cursor_fetch(query, municipality)
municipality_id = municipality_data[0]['id']
# Fetch regions from database based on selected city and municipality
query = '''
SELECT region FROM regions
WHERE municipality_id = ?;
'''
regions = cursor_fetch(query, municipality_id)
return regions
# |----- SEARCH HTML ROUTE ----|
@app.route('/search', methods=['GET', 'POST'])
@limiter.limit(f"{SEARCH_LIMIT}" if argparser.limiter else None)
@login_required
def search():
# Fetch cities for the initial rendering of the form
cities = cursor_fetch('SELECT DISTINCT city FROM cities')
# Get user data
user_id = session['user_id']
# Fetch user's primary submission to use it in the matching algorithm
query = '''
SELECT *
FROM submissions
WHERE user_id = ?
AND primary_submission = ?;
'''
primary_submission = cursor_fetch(
query,
user_id,
True
)
# POST requests are being handled with AJAX
if request.method == 'POST':
# Get user submitted form data
house_type = request.form.get('houseType')
square_meters = json.loads(request.form.get('squareMeters'))
rental = json.loads(request.form.get('rental'))
bedrooms = json.loads(request.form.get('bedrooms'))
bathrooms = json.loads(request.form.get('bathrooms'))
city = request.form.get('city')
municipality = request.form.get('municipality')
region = request.form.get('region')
tolerance = int(request.form.get('tolerance'))
exposure = 'public'
try:
# Ensure user form input for search submissions is valid
search_validation(
exposure,
house_type,
square_meters,
rental,
bedrooms,
bathrooms,
city,
municipality,
region
)
# Fetch all submissions from database according to search filters
query = '''
SELECT submissions.*,
users.email,
users.username,
regions.postal_code
FROM submissions
JOIN users ON submissions.user_id = users.id
JOIN regions ON submissions.region = regions.region
WHERE (submissions.house_type = ? OR ? = '')
AND ((submissions.square_meters >= ?
AND submissions.square_meters <= ?)
OR ? IS NULL OR ? = '')
AND ((submissions.rental >= ?
AND submissions.rental <= ?)
OR ? IS NULL OR ? = '')
AND ((submissions.bedrooms >= ?
AND submissions.bedrooms <= ?)
OR ? IS NULL OR ? = '')
AND ((submissions.bathrooms >= ?
AND submissions.bathrooms <= ?)
OR ? IS NULL OR ? = '')
AND (submissions.city = ? OR ? = '')
AND (submissions.municipality = ? OR ? = '')
AND (submissions.region = ? OR ? = '')
AND submissions.exposure = ?
AND submissions.user_id != ?;
'''
# Execute the query with the provided parameters
search_results = cursor_fetch(
query,
house_type, house_type,
square_meters['min'], square_meters['max'],
square_meters['min'], square_meters['max'],
rental['min'], rental['max'],
rental['min'], rental['max'],
bedrooms['min'], bedrooms['max'],
bedrooms['min'], bedrooms['max'],
bathrooms['min'], bathrooms['max'],
bathrooms['min'], bathrooms['max'],
city, city,
municipality, municipality,
region, region,
exposure,
user_id)
# Use matching algorithm in case the user has a primary submission
if len(primary_submission) > 0:
# Declare tolerance factors based on user's chosen tolerance percentage
TOLERANCE_FACTORS = tolerance_factors(tolerance)
# Shape the ranges of every house characteristic according to TOLERANCE_FACTORS
CRITERIA_RANGES = criteria_ranges(primary_submission, TOLERANCE_FACTORS)
# Add location matching score for each house in search results
location_matching(primary_submission, search_results)
# Add house factor-based matching score for each house in search results
house_matching(search_results, CRITERIA_RANGES)
# Calculate total matching score for each house in search results
matching_summary(search_results)
# Sort houses in search results based on total matching score; higher to lower
search_results = sorted(
search_results,
key=lambda result: result['total_matching_score'],
reverse=True
)
# Create a list of results that match to the user's primary submission
filtered_results = []
for result in search_results:
if result['total_matching_score'] > 16:
filtered_results.append(result)
return render_template(
'/search_results.html',
cities=cities,
search_results=search_results if not len(primary_submission) > 0 else filtered_results,
MATCHING_SCORES=MATCHING_SCORES,
primary_submission=primary_submission,
comma=comma,
whitespace=whitespace
)
except ValueError as err:
# Update log with ERROR msg
log(
f'''
{session['ip']}
USER[{session['username']}]: FAILED: Search submissions 'aborted': {err}
''',
level='WARNING',
indent=20
)
# Reload search page with default options selected
return render_template(
'/search.html',
cities=cities,
search_initial_page_load = True,
search=None,
primary_submission=primary_submission,
error=err,
whitespace=whitespace
)
else:
# Update log with INFO msg
log(
f'''
{session['ip']}
USER[{session['username']}]: NAVIGATION: @search.html
''',
indent=24
)
return render_template(
'/search.html',
cities=cities,
search_initial_page_load = True,
search=None,
primary_submission=primary_submission,
whitespace=whitespace