1
1
from flask import Flask , jsonify , make_response , request
2
- from flask_jwt_extended import JWTManager , create_access_token
2
+ from flask_jwt_extended import JWTManager , create_access_token , decode_token
3
3
import mysql .connector
4
4
from flask_cors import CORS
5
+ from apscheduler .schedulers .background import BackgroundScheduler
6
+ from datetime import datetime , timedelta
5
7
6
8
app = Flask (__name__ )
7
- CORS (app , resources = {r"/api/*" : {"origins" : "http://localhost:3000" }})
8
- app .config ["JWT_SECRET_KEY" ] = "your-secret-key" # Change this to a secure and secret key
9
+ CORS (app , resources = {r"/api/*" : {"origins" : "http://localhost:3000" }})
9
10
jwt = JWTManager (app )
10
11
11
- # Database configuration
12
+ # Database configurations
12
13
db_config = {
13
14
'user' : 'root' ,
14
15
'password' : 'root' ,
17
18
'database' : 'BrewandBrain'
18
19
}
19
20
20
- def get_db_connection ():
21
+ warehouse_db_config = {
22
+ 'user' : 'root' ,
23
+ 'password' : 'root' ,
24
+ 'host' : 'warehouse_db' ,
25
+ 'port' : '3308' ,
26
+ 'database' : 'BrewandBrain_warehouse'
27
+ }
28
+
29
+
30
+ def get_db_connection (config ):
21
31
try :
22
- connection = mysql .connector .connect (** db_config )
32
+ connection = mysql .connector .connect (** config )
23
33
return connection
24
34
except mysql .connector .Error as err :
25
35
print (f"Error connecting to the database: { err } " )
26
36
return None
27
37
28
38
# User-related functions
29
39
def write_to_users (data ):
30
- connection = get_db_connection ()
40
+ connection = get_db_connection (db_config )
31
41
if connection :
32
42
try :
33
43
cursor = connection .cursor ()
34
44
query = """
35
45
INSERT INTO Users
36
- (GoogleID, Username, Email, Password, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, School )
46
+ (GoogleID, Username, Email, Password, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, Occupation )
37
47
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
38
48
"""
49
+
39
50
values = (
40
- data [ 'google_id' ] , data ['username' ], data ['email' ], data ['password' ],
41
- data ['first_name ' ], data ['last_name ' ], data ['phone_number ' ], 'UName' , '2003-03-05' , 'Male' , 'Sample School'
51
+ 1 , data ['username' ], data ['email' ], data ['password' ],
52
+ data ['firstName ' ], data ['lastName ' ], data ['phoneNumber ' ], 'UName' , data [ 'birthdate' ], data [ 'gender' ], data [ 'occupation' ]
42
53
)
43
54
cursor .execute (query , values )
44
55
connection .commit ()
45
56
cursor .close ()
46
57
connection .close ()
47
58
except mysql .connector .Error as err :
48
59
print (f"Error writing to Users table: { err } " )
60
+
49
61
def update_user_details (user_id , updated_data ):
50
- connection = get_db_connection ()
62
+ connection = get_db_connection (db_config )
51
63
if connection :
52
64
try :
53
65
cursor = connection .cursor ()
@@ -66,8 +78,9 @@ def update_user_details(user_id, updated_data):
66
78
connection .close ()
67
79
except mysql .connector .Error as err :
68
80
print (f"Error updating user details: { err } " )
81
+
69
82
def get_all_users ():
70
- connection = get_db_connection ()
83
+ connection = get_db_connection (db_config )
71
84
if connection :
72
85
try :
73
86
cursor = connection .cursor (dictionary = True )
@@ -78,13 +91,14 @@ def get_all_users():
78
91
return results
79
92
except mysql .connector .Error as err :
80
93
print (f"Error: { err } " )
94
+
81
95
def get_user_by_id (user_id ):
82
- connection = get_db_connection ()
96
+ connection = get_db_connection (db_config )
83
97
if connection :
84
98
try :
85
99
cursor = connection .cursor (dictionary = True )
86
100
query = """
87
- SELECT UserID, GoogleID, Username, Email, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, School
101
+ SELECT UserID, GoogleID, Username, Email, FirstName, LastName, PhoneNumber, UName, Birthday, Gender, Occupation
88
102
FROM Users
89
103
WHERE UserID = %s
90
104
"""
@@ -96,14 +110,13 @@ def get_user_by_id(user_id):
96
110
except mysql .connector .Error as err :
97
111
print (f"Error fetching user by ID: { err } " )
98
112
99
-
100
113
def get_user_by_email_or_username (email_or_username ):
101
- connection = get_db_connection ()
114
+ connection = get_db_connection (db_config )
102
115
if connection :
103
116
try :
104
117
cursor = connection .cursor (dictionary = True )
105
118
query = """
106
- SELECT UserID, GoogleID, Username, Password, Email, UName, Birthday, Gender, School
119
+ SELECT UserID, GoogleID, Username, Password, Email, UName, Birthday, Gender, Occupation
107
120
FROM Users
108
121
WHERE Email = %s OR Username = %s
109
122
"""
@@ -114,63 +127,69 @@ def get_user_by_email_or_username(email_or_username):
114
127
return result
115
128
except mysql .connector .Error as err :
116
129
print (f"Error fetching user by email or username: { err } " )
117
- def create_reservation (user_id , reservation_data ):
118
- connection = get_db_connection ()
119
- if connection :
120
- try :
121
- cursor = connection .cursor ()
122
- query = """
123
- INSERT INTO Reservations
124
- (UserID, StartTime, EndTime, Seat)
125
- VALUES (%s, %s, %s, %s)
126
- """
127
- values = (
128
- user_id ,
129
- reservation_data ['STime' ],
130
- reservation_data ['ETime' ],
131
- reservation_data ['Seat' ],
132
- )
133
- cursor .execute (query , values )
134
- connection .commit ()
135
- cursor .close ()
136
- connection .close ()
137
- except mysql .connector .Error as err :
138
- print (f"Error creating reservation: { err } " )
139
- def get_user_reservations (user_id ):
140
- connection = get_db_connection ()
141
- if connection :
142
- try :
143
- cursor = connection .cursor (dictionary = True )
144
- query = """
145
- SELECT ReservationID, StartTime, EndTime, Seat
146
- FROM Reservations
147
- WHERE UserID = %s
148
- """
149
- cursor .execute (query , (user_id ,))
150
- results = cursor .fetchall ()
151
- cursor .close ()
152
- connection .close ()
153
- return results
154
- except mysql .connector .Error as err :
155
- print (f"Error fetching user reservations: { err } " )
156
-
157
- @app .route ('/api/sign-in' , methods = ['POST' ])
158
- def sign_in ():
159
- data = request .get_json ()
160
- user = get_user_by_email_or_username (data ['login' ])
161
-
162
- if user and user ['Password' ] == data ['password' ]:
163
- access_token = create_access_token (identity = user ['Username' ])
164
-
165
- # Create a response object
166
- response = make_response (jsonify (access_token = access_token ), 200 )
167
-
168
- # Set HttpOnly flag for the access token cookie
169
- response .set_cookie ('access_token' , value = access_token , httponly = True )
170
-
171
- return response
172
- else :
173
- return jsonify ({"message" : "Invalid login credentials" }), 401
130
+
131
+ def perform_warehouse_process ():
132
+ try :
133
+ # Connect to operational database
134
+ operational_connection = get_db_connection (db_config )
135
+ if operational_connection :
136
+ operational_cursor = operational_connection .cursor (dictionary = True )
137
+
138
+ # Connect to warehouse database
139
+ warehouse_connection = get_db_connection (warehouse_db_config )
140
+ if warehouse_connection :
141
+ warehouse_cursor = warehouse_connection .cursor ()
142
+
143
+ try :
144
+ # Extract data from the operational database
145
+ operational_cursor .execute ("""
146
+ SELECT UserID, School, Occupation
147
+ FROM Users
148
+ """ )
149
+ users_data = operational_cursor .fetchall ()
150
+
151
+ # Transform and load data into the warehouse
152
+ for user in users_data :
153
+ # Fetch reservations for the current user
154
+ operational_cursor .execute ("""
155
+ SELECT StartTime, EndTime
156
+ FROM Reservations
157
+ WHERE UserID = %s
158
+ """ , (user ['UserID' ],))
159
+ reservations_data = operational_cursor .fetchall ()
160
+
161
+ # Insert user and reservation data into the warehouse
162
+ for reservation in reservations_data :
163
+ warehouse_cursor .execute (
164
+ """
165
+ INSERT INTO UserSummary (UserID, School, Occupation, StartTime, EndTime)
166
+ VALUES (%s, %s, %s, %s, %s)
167
+ """ ,
168
+ (user ['UserID' ], user ['School' ], user ['Occupation' ],
169
+ reservation ['StartTime' ], reservation ['EndTime' ])
170
+ )
171
+
172
+ # Commit changes to the warehouse database
173
+ warehouse_connection .commit ()
174
+ print ("Warehouse process completed successfully." )
175
+ except Exception as e :
176
+ print (f"Error during ETL process: { e } " )
177
+ warehouse_connection .rollback () # Rollback changes in case of an error
178
+
179
+ warehouse_cursor .close ()
180
+ warehouse_connection .close ()
181
+
182
+ operational_cursor .close ()
183
+ operational_connection .close ()
184
+
185
+ except Exception as e :
186
+ print (f"Error performing warehouse process: { e } " )
187
+
188
+ # Initialize the BackgroundScheduler
189
+ scheduler = BackgroundScheduler ()
190
+
191
+ # Add the scheduled job to run the ETL process every 168 hours or 1 week
192
+ scheduler .add_job (perform_warehouse_process , 'interval' , hours = 168 )
174
193
175
194
@app .route ('/api/create-account' , methods = ['POST' ])
176
195
def create_account ():
@@ -183,7 +202,43 @@ def create_account():
183
202
print (f"Error creating account: { e } " )
184
203
return jsonify (message = 'Error creating account' ), 500
185
204
186
- @app .route ('/api/update-account/<int:user_id>' , methods = ['PUT' ])
205
+
206
+ @app .route ('/api/sign-in' , methods = ['POST' ])
207
+ def sign_in ():
208
+ data = request .get_json ()
209
+ user = get_user_by_email_or_username (data ['login' ])
210
+
211
+ if user and user ['Password' ] == data ['password' ]:
212
+
213
+ # token = create_access_token(identity=user['Username'])
214
+
215
+ # # Access the access_token directly from create_access_token
216
+ # access_token = decode_token(token)['identity']
217
+ # print(access_token)
218
+
219
+ # Fetch additional user data
220
+ user_data = get_user_by_id (user ['UserID' ])
221
+
222
+ # Create a response object
223
+ response_data = {
224
+ 'user_data' : {
225
+ 'UserID' : user_data ['UserID' ],
226
+ 'Username' : user_data ['Username' ],
227
+ 'Email' : user_data ['Email' ],
228
+ 'PhoneNumber' : user_data ['PhoneNumber' ],
229
+ 'Gender' : user_data ['Gender' ],
230
+ 'Occupation' : user_data ['Occupation' ],
231
+
232
+ # Add other user data fields as needed
233
+ }
234
+ }
235
+
236
+ response = make_response (jsonify (response_data ), 200 )
237
+
238
+ return response
239
+ else :
240
+ return jsonify ({"message" : "Invalid login credentials" }), 401
241
+ @app .route ('/api/update-account/' , methods = ['PUT' ])
187
242
def update_account (user_id ):
188
243
try :
189
244
updated_data = request .get_json ()
@@ -194,16 +249,25 @@ def update_account(user_id):
194
249
print (f"Error updating account: { e } " )
195
250
return jsonify (message = 'Error updating account' ), 500
196
251
197
- @app .route ('/api/reservations' , methods = ['POST' ])
198
- def make_reservation ():
199
- try :
200
- data = request .get_json ()
201
- user_id = 1 # Replace with the actual user ID; you need to identify the user somehow
202
- result = create_reservation (user_id , data )
203
- return jsonify (result )
204
- except Exception as e :
205
- print (f"Error creating reservation: { e } " )
206
- return jsonify (error = 'Error creating reservation' ), 500
252
+ # @app.route('/api/get-reservations/<int:user_id>', methods=['GET'])
253
+ # def get_reservations(user_id):
254
+ # try:
255
+ # reservations = get_user_reservations(user_id)
256
+ # return jsonify(reservations)
257
+ # except Exception as e:
258
+ # print(f"Error fetching reservations: {e}")
259
+ # return jsonify(error='Error fetching reservations'), 500
260
+
261
+ # @app.route('/api/reservations', methods=['POST'])
262
+ # def make_reservation():
263
+ # try:
264
+ # data = request.get_json()
265
+ # user_id = 5 # Replace with the actual user ID; you need to identify the user somehow
266
+ # result = create_reservation(user_id, data)
267
+ # return jsonify(result)
268
+ # except Exception as e:
269
+ # print(f"Error creating reservation: {e}")
270
+ # return jsonify(error='Error creating reservation'), 500
207
271
208
272
209
273
# Additional user-related functions
@@ -227,4 +291,5 @@ def index():
227
291
return jsonify ({'User Data' : 'Sample user created' })
228
292
229
293
if __name__ == '__main__' :
294
+ scheduler .start ()
230
295
app .run (host = '0.0.0.0' , debug = True )
0 commit comments