-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
729 lines (646 loc) · 24.9 KB
/
app.py
File metadata and controls
729 lines (646 loc) · 24.9 KB
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
from flask import Flask, request, jsonify, render_template, render_template_string, session, redirect, url_for
import mysql.connector
import hashlib
import os
from dotenv import load_dotenv
from mysql.connector.errors import DatabaseError
from datetime import datetime
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# Configure FLASK_DEBUG from environment variable
app.config['DEBUG'] = os.environ.get('FLASK_DEBUG')
load_dotenv()
# Access environment variables as if they came from the actual environment
GCP_DB_HOST = os.getenv('GCP_DB_HOST')
GCP_DB_USER = os.getenv('GCP_DB_USER')
GCP_DB_PASSWORD = os.getenv('GCP_DB_PASSWORD')
GCP_DB_NAME = os.getenv('GCP_DB_NAME')
APP_SECRET_KEY = os.getenv('APP_SECRET_KEY')
# Database configuration from environment variables
app.secret_key = APP_SECRET_KEY
db_config = {
'host': GCP_DB_HOST,
'user': GCP_DB_USER,
'password': GCP_DB_PASSWORD,
'database': GCP_DB_NAME,
}
# Connect to MySQL
def get_db_connection():
return mysql.connector.connect(**db_config)
# Helper function to hash passwords
def hash_password(password):
return hashlib.md5(password.encode()).hexdigest()
@app.route('/')
def home():
"""Redirect to events page if logged in, otherwise to login page."""
if 'user' in session and session['is_admin']==0:
return redirect(url_for('events_page'))
return redirect(url_for('login'))
@app.route('/admin')
def index():
return render_template('index.html')
# CRUD APIs
# Create User
@app.route('/users/create', methods=['POST'])
def create_user():
data = request.json
conn = None
try:
hashed_password = hash_password(data['password'])
conn = get_db_connection()
cursor = conn.cursor()
query = "INSERT INTO Users (username, name, password, is_admin) VALUES (%s, %s, %s, %s)"
cursor.execute(query, (data['username'], data['name'], hashed_password, data['is_admin']))
conn.commit()
return jsonify({'message': 'User created successfully!'}), 201
except DatabaseError as e:
if conn:
conn.rollback()
print(e)
error_code = e.args[0]
if error_code == 1205:
return jsonify({'error': 'Lock wait timeout exceeded. Please try again later.'}), 500
else:
return jsonify({'error': f'Database error: {str(e)}'}), 500
except Exception as e:
if conn:
conn.rollback()
return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
# Create Ticket
@app.route('/tickets/create', methods=['POST'])
def create_ticket():
data = request.json
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor()
query = "INSERT INTO Tickets (ticket_id, event_title, ticket_price, fee, total_price, quantity, full_section, section, row_num) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
cursor.execute(query, (data["ticket_id"], data["event_title"], data["ticket_price"], data["fee"], data["total_price"], data["quantity"], data["full_section"], data["section"], data["row_num"]))
conn.commit()
return jsonify({'message': 'Ticket created successfully!'}), 201
except DatabaseError as e:
if conn:
conn.rollback()
print(e)
error_code = e.args[0]
if error_code == 1205:
return jsonify({'error': 'Lock wait timeout exceeded. Please try again later.'}), 500
else:
return jsonify({'error': f'Database error: {str(e)}'}), 500
except Exception as e:
if conn:
conn.rollback()
return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
# Create Event
@app.route('/events/create', methods=['POST'])
def create_event():
data = request.json
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor()
query = """
INSERT INTO Events (event_title, event_url, datetime_local, location_name, promoter_name)
VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(query, (data["event_title"], data["event_url"], data["datetime_local"], data["location_name"], data["promoter_name"]))
conn.commit()
return jsonify({'message': 'Events created successfully!'}), 201
except DatabaseError as e:
if conn:
conn.rollback() # Instantly remove locks by rolling back the transaction
print(e)
error_code = e.args[0]
if error_code == 1205: # Lock wait timeout exceeded
return jsonify({'error': 'Lock wait timeout exceeded. Please try again later.'}), 500
else:
return jsonify({'error': f'Database error: {str(e)}'}), 500
except Exception as e:
if conn:
conn.rollback() # Ensure rollback for any unexpected error
print(e)
return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
# Read Users
@app.route('/users/records', methods=['GET'])
def get_users():
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT username, name, is_admin FROM Users")
records = cursor.fetchall()
conn.close()
return jsonify(records)
# Read Tickets
@app.route('/tickets/records', methods=['GET'])
def get_tickets():
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM Tickets LIMIT 15")
records = cursor.fetchall()
conn.close()
return jsonify(records)
# Read Events
@app.route('/events/records', methods=['GET'])
def get_events():
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT * FROM Events LIMIT 10")
records = cursor.fetchall()
conn.close()
return jsonify(records)
# Update User
@app.route('/users/update/<old_username>', methods=['PUT'])
def update_user(old_username):
print(request.json)
conn = None
data = request.json
try:
conn = get_db_connection()
cursor = conn.cursor()
hashed_password = hash_password(data['password']) if 'password' in data else None
query = "UPDATE Users SET username = %s, name = %s, password = %s, is_admin = %s WHERE username = %s"
cursor.execute(query, (data['new_username'], data['name'], hashed_password, data['is_admin'], old_username))
conn.commit()
return jsonify({'message': 'User updated successfully!'})
except DatabaseError as e:
if conn:
conn.rollback()
print(e)
error_code = e.args[0]
if error_code == 1205:
return jsonify({'error': 'Lock wait timeout exceeded. Please try again later.'}), 500
else:
return jsonify({'error': f'Database error: {str(e)}'}), 500
except Exception as e:
if conn:
conn.rollback()
return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
# Update Ticket
@app.route('/tickets/update/<ticket_id>', methods=['PUT'])
def update_ticket(ticket_id):
conn = None
data = request.json
try:
conn = get_db_connection()
cursor = conn.cursor()
# ticket_id, event_title, ticket_price, fee, total_price, quantity, full_section, section, row_num
query = "UPDATE Tickets SET event_title = %s, ticket_price = %s, fee = %s, total_price = %s, quantity = %s, full_section = %s, section = %s, row_num = %s WHERE ticket_id = %s"
cursor.execute(query, (data['event_title'], data['ticket_price'], data['fee'], data['total_price'], data['quantity'], data['full_section'], data['section'], data['row_num'], data["ticket_id"]))
conn.commit()
return jsonify({'message': 'Ticket updated successfully!'})
except DatabaseError as e:
if conn:
conn.rollback()
print(e)
error_code = e.args[0]
if error_code == 1205:
return jsonify({'error': 'Lock wait timeout exceeded. Please try again later.'}), 500
else:
return jsonify({'error': f'Database error: {str(e)}'}), 500
except Exception as e:
if conn:
conn.rollback()
return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
# Update Events
@app.route('/events/update/<old_event_title>', methods=['PUT'])
def update_event(old_event_title):
conn = None
data = request.json
try:
conn = get_db_connection()
cursor = conn.cursor()
# event_title, event_url, datetime_local, location_name, promoter_name
query = "UPDATE Events SET event_title = %s, event_url = %s, datetime_local = %s, location_name = %s, promoter_name = %s WHERE event_title = %s"
cursor.execute(query, (data['event_title'], data['event_url'], data['datetime_local'], data['location_name'], data['promoter_name'], old_event_title))
conn.commit()
return jsonify({'message': 'Event updated successfully!'})
except DatabaseError as e:
if conn:
conn.rollback()
print(e)
error_code = e.args[0]
if error_code == 1205:
return jsonify({'error': 'Lock wait timeout exceeded. Please try again later.'}), 500
else:
return jsonify({'error': f'Database error: {str(e)}'}), 500
except Exception as e:
if conn:
conn.rollback()
return jsonify({'error': f'An unexpected error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
# Delete User
@app.route('/users/delete/<username>', methods=['DELETE'])
def delete_user(username):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("DELETE FROM Users WHERE username = %s", (username,))
conn.commit()
conn.close()
return jsonify({'message': 'User deleted successfully!'})
# Delete Ticket
@app.route('/tickets/delete/<ticket_id>', methods=['DELETE'])
def delete_ticket(ticket_id):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("DELETE FROM Tickets WHERE ticket_id = %s", (ticket_id,))
conn.commit()
conn.close()
return jsonify({'message': 'Ticket deleted successfully!'})
# Delete Event
@app.route('/events/delete/<event_title>', methods=['DELETE'])
def delete_event(event_title):
conn = get_db_connection()
cursor = conn.cursor()
try:
# Set isolation level
cursor.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
# Start transaction
conn.start_transaction()
# Insert the new wishlist entry
cursor.execute("""
INSERT INTO Notifications (username, event_title, message)
SELECT
w.username,
e.event_title,
CONCAT('The event "', e.event_title,
' at ', l.location_name, ' (', l.city, ', ', l.state, ') ',
'has been cancelled. ',
'There are ', other_events.event_count, ' other events happening in ', l.city, '. ',
'Check them out!') AS message
FROM WishList w
JOIN Events e ON w.event_title = e.event_title
JOIN Locations l ON e.location_name = l.location_name
JOIN (
SELECT city, COUNT(*) as event_count
FROM Events natural join Locations
WHERE event_title != %s
GROUP BY city
) other_events ON l.city = other_events.city
WHERE e.event_title = %s;
""", (event_title, event_title))
# Insert notification
cursor.execute("""
DELETE FROM Events
WHERE event_title = %s;
""", (event_title,))
# Commit the transaction
conn.commit()
return jsonify({'message': 'Event deleted successfully!'}), 200
except Exception as e:
conn.rollback()
print(e)
return jsonify({'error': f'An error occurred: {str(e)}'}), 500
finally:
cursor.close()
conn.close()
# ----------------------------------------------------------------------------------
@app.route('/events')
def view_events():
"""Display a list of events for end-users."""
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT event_title, datetime_local, location_name, promoter_name, city FROM Events natural join Locations LIMIT 150")
events = cursor.fetchall()
return jsonify(events)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred while fetching events: {str(e)}'}), 500
finally:
if conn:
conn.close()
@app.route('/events-page')
def events_page():
if 'user' not in session:
return redirect(url_for('login'))
return render_template('events.html', username=session['user'], check_notifications=True)
# Not Used
@app.route('/tickets')
def view_tickets():
"""Display a list of tickets for end-users."""
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT ticket_id, event_title, ticket_price, total_price, quantity, section, row_num FROM Tickets LIMIT 15")
tickets = cursor.fetchall()
return render_template('tickets.html', tickets=tickets)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred while fetching tickets: {str(e)}'}), 500
finally:
if conn:
conn.close()
@app.route('/tickets/<event_title>')
def view_tickets_by_title(event_title):
"""Display a list of tickets for a given event title."""
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
query = """
SELECT distinct t.section, t.row_num, t.quantity, t.total_price
FROM Tickets t
WHERE t.event_title = %s
"""
cursor.execute(query, (event_title,))
tickets = cursor.fetchall()
if not tickets:
return jsonify({'message': f'No tickets found for event: {event_title}'}), 404
return jsonify(tickets)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred while fetching tickets: {str(e)}'}), 500
finally:
if conn:
conn.close()
@app.route('/tickets-page/<event_title>')
def tickets_page(event_title):
"""Serve the tickets.html page for a specific event."""
return render_template('tickets.html', event_title=event_title)
#Login
@app.route('/login', methods=['GET', 'POST'])
def login():
"""Login page logic."""
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if not username or not password:
return render_template('login.html', error="Please enter both username and password.")
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
try:
cursor.execute(
"SELECT username, password, is_admin FROM Users WHERE username = %s",
(username,)
)
user = cursor.fetchone()
if user and user['password'] == hash_password(password):
session['user'] = user['username']
session['is_admin'] = user['is_admin']
if user['is_admin'] == 1:
return redirect('/admin')
else:
return redirect('/events-page')
else:
return render_template('login.html', error="Invalid username or password.")
except Exception as e:
print(e)
return render_template('login.html', error="An error occurred. Please try again.")
finally:
conn.close()
return render_template('login.html')
#Logout
@app.route('/logout')
def logout():
"""Log the user out."""
session.pop('user', None)
return redirect(url_for('login'))
@app.route('/wishlist-page')
def wishlist_page():
"""Render the wishlist page."""
if 'user' not in session:
return redirect('/login') # Redirect to login if the user is not logged in
return render_template('wishlist.html', username=session['user'])
@app.route('/wishlist', methods=['POST'])
def add_to_wishlist():
"""Add an event to the wishlist."""
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
username = session['user']
event_title = request.json.get('event_title')
if not event_title:
return jsonify({'error': 'Event title is required'}), 400
conn = get_db_connection()
cursor = conn.cursor()
try:
wishlist_date = datetime.now()
# Set isolation level
cursor.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ")
# Start transaction
conn.start_transaction()
# Insert the new wishlist entry
cursor.execute("""
INSERT INTO WishList (username, event_title, wishlist_date)
VALUES (%s, %s, %s)
ON DUPLICATE KEY UPDATE wishlist_date = VALUES(wishlist_date)
""", (username, event_title, wishlist_date))
# Insert notification
cursor.execute("""
INSERT INTO Notifications (username, event_title, message)
SELECT
%s,
e.event_title,
CONCAT('You have added "', e.event_title, '" to your wishlist. ',
' at ', e.location_name, ' (', l.city, ', ', l.state, '). ',
'Promoted by ', e.promoter_name, '. ',
'Currently, ', COUNT(w.username), ' user(s) have wishlisted this event, ',
'including you. ')
FROM Events e
JOIN Locations l ON e.location_name = l.location_name
LEFT JOIN WishList w ON e.event_title = w.event_title
WHERE e.event_title = %s
GROUP BY e.event_title, e.location_name, l.city, l.state, e.promoter_name
""", (username, event_title))
# Commit the transaction
conn.commit()
return jsonify({'message': 'Event added to wishlist successfully'}), 200
except Exception as e:
conn.rollback()
print(e)
return jsonify({'error': f'An error occurred: {str(e)}'}), 500
finally:
cursor.close()
conn.close()
@app.route('/wishlist', methods=['GET'])
def fetch_wishlist():
"""Fetch wishlist for the logged-in user."""
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
username = session['user']
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute(
"""
SELECT W.event_title, E.datetime_local, E.location_name, E.promoter_name
FROM WishList W
JOIN Events E ON W.event_title = E.event_title
WHERE W.username = %s
""",
(username,)
)
wishlist_events = cursor.fetchall()
return jsonify(wishlist_events), 200
except Exception as e:
print(e)
return jsonify({'error': f'Error fetching wishlist: {str(e)}'}), 500
finally:
conn.close()
@app.route('/wishlist', methods=['DELETE'])
def remove_from_wishlist():
"""Remove an event from the wishlist."""
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
username = session['user']
event_title = request.json.get('event_title')
if not event_title:
return jsonify({'error': 'Event title is required'}), 400
try:
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute(
"""
DELETE FROM WishList
WHERE username = %s AND event_title = %s
""",
(username, event_title)
)
conn.commit()
return jsonify({'message': f'Event "{event_title}" removed from wishlist successfully'}), 200
except Exception as e:
print(e)
return jsonify({'error': f'Error removing event: {str(e)}'}), 500
finally:
conn.close()
@app.route('/popular-events')
def get_popular_events():
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("CALL GetPopularEvents(10)")
popular_events = cursor.fetchall()
return jsonify(popular_events)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred while fetching popular events: {str(e)}'}), 500
finally:
if conn:
conn.close()
@app.route('/top-cities-events')
def top_cities_events():
"""Fetch events happening in the top 5 major cities."""
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
try:
# Query events happening in the top 5 major cities
query = """
call GetTopCitiesEvents(10);
"""
cursor.execute(query)
events = cursor.fetchall()
return jsonify(events)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred: {str(e)}'}), 500
finally:
conn.close()
@app.route('/filtered-events')
def filtered_events():
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
query = request.args.get('query', '').lower()
city = request.args.get('city', 'all')
start_date = request.args.get('start_date', '')
end_date = request.args.get('end_date', '')
tab = request.args.get('tab', 'all')
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
if tab == 'popular':
cursor.execute("CALL GetPopularEvents(10)")
events = cursor.fetchall()
else:
sql_query = """
SELECT event_title, datetime_local, location_name, promoter_name, city
FROM Events
NATURAL JOIN Locations
WHERE LOWER(event_title) LIKE %s
"""
params = [f'%{query}%']
if city != 'all':
sql_query += " AND city = %s"
params.append(city)
if start_date:
sql_query += " AND datetime_local >= %s"
params.append(start_date)
if end_date:
sql_query += " AND datetime_local <= %s"
params.append(end_date)
if tab == 'major':
sql_query += """ AND city in ( Select city from
(select city, count(event_title) from Locations natural join Events group by city order by 2 desc limit 5) z
)"""
sql_query += " LIMIT 150"
cursor.execute(sql_query, tuple(params))
events = cursor.fetchall()
# Apply client-side filtering for the popular tab
if tab == 'popular':
events = [event for event in events if
(city == 'all' or event['city'] == city) and
(not start_date or str(event['datetime_local']) >= start_date) and
(not end_date or str(event['datetime_local']) <= end_date) and
query in event['event_title'].lower()]
return jsonify(events)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred while fetching events: {str(e)}'}), 500
finally:
if conn:
conn.close()
@app.route('/get_notifications')
def get_notifications():
if 'user' not in session:
return jsonify({'error': 'Unauthorized access'}), 401
username = session['user']
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor(dictionary=True)
# Fetch unread notifications
cursor.execute("""
SELECT notification_id, message FROM Notifications
WHERE username = %s AND is_read = 0
""", (username,))
notifications = cursor.fetchall()
# Mark notifications as read
if notifications:
cursor.execute("""
UPDATE Notifications
SET is_read = 1
WHERE username = %s AND is_read = 0
""", (username,))
conn.commit()
return jsonify(notifications)
except Exception as e:
print(e)
return jsonify({'error': f'An error occurred: {str(e)}'}), 500
finally:
if conn:
conn.close()
if __name__ == '__main__':
app.run()