-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
379 lines (321 loc) · 12.8 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
from flask import Flask, request, jsonify
from werkzeug.security import generate_password_hash, check_password_hash
from flask_cors import CORS
from flask_cors import CORS, cross_origin
import sqlite3
from db_utils import db_init, add_user, get_all_users, update_user_info, delete_user, get_password_hash_by_username, create_appointment, get_appointments_by_teacher, get_appointments_by_student, update_appointment_status, delete_appointment
from datetime import datetime, timedelta
from flask import Flask, request, jsonify
import sqlite3
from datetime import datetime, timedelta
app = Flask(__name__)
CORS(app)
# # 初始化数据库
# db_init()
@app.route('/', methods=['OPTIONS'])
@cross_origin()
def handle_options_request():
response = jsonify({'message': 'This is the response to OPTIONS request'})
response.headers.add('Access-Control-Allow-Methods', 'GET, POST')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
return response
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
username = data.get('username')
password = data.get('password')
role = data.get('role')
if not username or not password or not role:
return jsonify({'message': 'Missing username, password, or role'}), 400
try:
add_user(username, password, role)
return jsonify({'message': 'User registered successfully'}), 201
except Exception as e:
return jsonify({'message': str(e)}), 500
@app.route('/login', methods=['POST'])
@cross_origin()
def login():
data = request.get_json()
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({'message': 'Missing username or password'}), 400
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('SELECT user_id, password_hash, role FROM users WHERE username = ?', (username,))
result = c.fetchone()
conn.close()
if result:
user_id, password_hash, role = result
if check_password_hash(password_hash, password):
return jsonify({'message': 'Login successful', 'username': username, 'role': role, 'user_id': user_id}), 200
else:
return jsonify({'message': 'Invalid username or password'}), 401
else:
return jsonify({'message': 'Invalid username or password'}), 401
# 管理员 API 接口
@app.route('/admin/users', methods=['GET'])
def get_users():
users = get_all_users()
users_list = []
for user in users:
user_dict = {
'user_id': user[0],
'username': user[1],
'password': user[2],
'role': user[3]
}
users_list.append(user_dict)
return jsonify(users_list), 200
@app.route('/admin/appointments', methods=['GET'])
def get_all_appointments():
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('SELECT * FROM appointments')
appointments = c.fetchall()
conn.close()
appointments_list = []
for appointment in appointments:
appointments_list.append({
'appointment_id': appointment[0],
'student_id': appointment[1],
'teacher_id': appointment[2],
'date': appointment[3],
'start_time': appointment[4],
'end_time': appointment[5],
'status': appointment[6],
})
return jsonify(appointments_list), 200
@app.route('/admin/users/<int:user_id>', methods=['PUT'])
def modify_user(user_id):
data = request.get_json()
username = data.get('username')
password = data.get('password')
role = data.get('role')
try:
update_user_info(user_id, username, password, role)
return jsonify({'message': 'User information updated successfully'}), 200
except Exception as e:
return jsonify({'message': str(e)}), 500
@app.route('/admin/users/<int:user_id>', methods=['DELETE'])
def remove_user(user_id):
try:
delete_user(user_id)
return jsonify({'message': 'User deleted successfully'}), 200
except Exception as e:
return jsonify({'message': str(e)}), 500
@app.route('/user/<int:user_id>', methods=['GET'])
def get_user_info(user_id):
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('SELECT * FROM users WHERE user_id = ?', (user_id,))
user = c.fetchone()
if user:
user_info = {
'user_id': user[0],
'username': user[1],
'role': user[3]
}
if user[3] == 'teacher':
c.execute('SELECT * FROM teachers WHERE user_id = ?', (user_id,))
teacher = c.fetchone()
if teacher:
user_info.update({
'name': teacher[2],
'gender': teacher[3],
'title': teacher[4],
'department': teacher[5],
'office_number': teacher[6],
'phone': teacher[7]
})
elif user[3] == 'student':
c.execute('SELECT * FROM students WHERE user_id = ?', (user_id,))
student = c.fetchone()
if student:
user_info.update({
'name': student[2],
'gender': student[3],
'student_number': student[4],
'class': student[5],
'phone': student[6]
})
conn.close()
return jsonify(user_info), 200
conn.close()
return jsonify({'message': 'User not found'}), 404
@app.route('/user/<int:user_id>', methods=['PUT'])
def update_user_info(user_id):
data = request.get_json()
print(f"Received data from frontend: {data}") # 打印接收到的数据
username = data.get('username')
role = data.get('role')
# 添加日志打印以调试
print(f"Updating user {user_id} with username: {username}, role: {role}")
if not username or not role:
return jsonify({'message': 'Username and role are required'}), 400
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
try:
c.execute('UPDATE users SET username = ?, role = ? WHERE user_id = ?', (username, role, user_id))
if role == 'teacher':
name = data.get('name')
gender = data.get('gender')
title = data.get('title')
department = data.get('department')
office_number = data.get('office_number')
phone = data.get('phone')
c.execute('''
INSERT INTO teachers (user_id, name, gender, title, department, office_number, phone)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
name = excluded.name,
gender = excluded.gender,
title = excluded.title,
department = excluded.department,
office_number = excluded.office_number,
phone = excluded.phone
''', (user_id, name, gender, title, department, office_number, phone))
elif role == 'student':
name = data.get('name')
gender = data.get('gender')
student_number = data.get('student_number')
class_ = data.get('class')
phone = data.get('phone')
c.execute('''
INSERT INTO students (user_id, name, gender, student_number, class, phone)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(user_id) DO UPDATE SET
name = excluded.name,
gender = excluded.gender,
student_number = excluded.student_number,
class = excluded.class,
phone = excluded.phone
''', (user_id, name, gender, student_number, class_, phone))
conn.commit()
except sqlite3.Error as e:
conn.rollback()
print(f"Database error: {e}")
return jsonify({'message': 'An error occurred while updating user information'}), 500
finally:
conn.close()
return jsonify({'message': 'User information updated successfully'}), 200
@app.route('/teacher/timetable/<int:user_id>', methods=['GET'])
def get_teacher_timetable(user_id):
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('SELECT availability_id, date, start_time, end_time FROM teacher_availability WHERE teacher_id = ?', (user_id,))
timetable = c.fetchall()
conn.close()
# 确保返回的数据格式为 JSON
return jsonify([{
'id': row[0],
'date': row[1],
'start_time': row[2],
'end_time': row[3]
} for row in timetable]), 200
@app.route('/teacher/timetable', methods=['POST'])
def add_teacher_timetable():
data = request.get_json()
teacher_id = data.get('teacher_id')
date = data.get('date')
start_time = data.get('start_time')
end_time = data.get('end_time')
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('''
INSERT INTO teacher_availability (teacher_id, date, start_time, end_time)
VALUES (?, ?, ?, ?)
''', (teacher_id, date, start_time, end_time))
conn.commit()
conn.close()
return jsonify({'message': 'Time slot added successfully'}), 201
@app.route('/teacher/timetable/<int:id>', methods=['DELETE'])
def delete_teacher_timetable(id):
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('DELETE FROM teacher_availability WHERE availability_id = ?', (id,))
conn.commit()
conn.close()
return jsonify({'message': 'Time slot deleted successfully'}), 200
@app.route('/teacher/appointments/<int:user_id>', methods=['GET'])
def get_teacher_appointments(user_id):
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('''
SELECT a.appointment_id, s.name AS student_name, a.date, a.start_time, a.end_time, a.status
FROM appointments a
JOIN students s ON a.student_id = s.student_id
WHERE a.teacher_id = ?
''', (user_id,))
appointments = c.fetchall()
conn.close()
return jsonify(appointments), 200
@app.route('/teacher/appointments/<int:id>', methods=['PUT'])
def update_appointment_status(id):
data = request.get_json()
status = data.get('status')
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('UPDATE appointments SET status = ? WHERE appointment_id = ?', (status, id))
conn.commit()
conn.close()
return jsonify({'message': 'Appointment status updated successfully'}), 200
@app.route('/teacher/timetable/default', methods=['POST'])
def set_default_timetable():
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
# 获取所有教师的 ID
c.execute('SELECT user_id FROM users WHERE role = "teacher"')
teachers = c.fetchall()
# 获取当前日期和未来三天的日期
today = datetime.now()
dates = [(today + timedelta(days=i)).strftime('%Y-%m-%d') for i in range(1, 4)]
# 定义默认的空闲时间段
default_times = [
('08:00', '09:00'),
('09:00', '10:00'),
('10:00', '11:00'),
('14:00', '15:00'),
('15:00', '16:00'),
('16:00', '17:00')
]
# 为每个教师分配未来三天的默认空闲时间
for teacher in teachers:
teacher_id = teacher[0]
for date in dates:
for start_time, end_time in default_times:
c.execute('''
INSERT INTO teacher_availability (teacher_id, date, start_time, end_time)
VALUES (?, ?, ?, ?)
''', (teacher_id, date, start_time, end_time))
conn.commit()
conn.close()
return jsonify({'message': 'Default timetable set successfully for all teachers'}), 201
# 学生 API 接口
@app.route('/student/availability/<int:teacher_id>', methods=['GET'])
def get_teacher_availability(teacher_id):
conn = sqlite3.connect('school_appointment.db')
c = conn.cursor()
c.execute('SELECT * FROM teacher_availability WHERE teacher_id = ?', (teacher_id,))
availability = c.fetchall()
conn.close()
return jsonify(availability), 200
@app.route('/student/appointments', methods=['POST'])
def book_appointment():
data = request.get_json()
student_id = data.get('student_id')
teacher_id = data.get('teacher_id')
date = data.get('date')
start_time = data.get('start_time')
end_time = data.get('end_time')
try:
create_appointment(student_id, teacher_id, date, start_time, end_time)
return jsonify({'message': 'Appointment booked successfully'}), 201
except Exception as e:
return jsonify({'message': str(e)}), 500
@app.route('/student/appointments/<int:student_id>', methods=['GET'])
def get_student_appointments(student_id):
appointments = get_appointments_by_student(student_id)
return jsonify(appointments), 200
if __name__ == '__main__':
app.run(debug=True)