-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstudents_app.py
More file actions
52 lines (46 loc) · 1.33 KB
/
students_app.py
File metadata and controls
52 lines (46 loc) · 1.33 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
from flask import Flask, jsonify
import pymysql
from pymysql.cursors import DictCursor
app = Flask(__name__)
# MySQL configuration for XAMPP
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'students_db'
def get_db_connection():
return pymysql.connect(
host=app.config['MYSQL_HOST'],
user=app.config['MYSQL_USER'],
password=app.config['MYSQL_PASSWORD'],
database=app.config['MYSQL_DB'],
cursorclass=DictCursor,
autocommit=True
)
@app.route('/')
def home():
return "Students API - Access /students endpoint"
@app.route('/students')
def get_students():
connection = get_db_connection()
try:
with connection.cursor() as cursor:
cursor.execute("""
SELECT name, program
FROM students
ORDER BY name
""")
students = cursor.fetchall()
return jsonify({
'success': True,
'count': len(students),
'students': students
})
except Exception as e:
return jsonify({
'success': False,
'error': str(e)
}), 500
finally:
connection.close()
if __name__ == '__main__':
app.run(debug=True, port=5000)