Skip to content

Commit 6f7e6a6

Browse files
eatulrajputAtul Rajput
authored andcommitted
Refactor Validation
Signed-off-by: Atul Rajput <[email protected]>
1 parent 99dae2a commit 6f7e6a6

File tree

1 file changed

+27
-15
lines changed

1 file changed

+27
-15
lines changed

flask-sqlite/app.py

Lines changed: 27 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,27 @@
77

88
db.init_app(app)
99

10+
# 🔧 Validation Helper Function
11+
def validate_student_data(data, partial=False):
12+
if not data:
13+
return "Missing JSON body"
14+
15+
if not partial:
16+
if 'name' not in data:
17+
return "Missing 'name'"
18+
if 'age' not in data:
19+
return "Missing 'age'"
20+
21+
if 'name' in data:
22+
if not isinstance(data['name'], str) or not data['name'].strip():
23+
return "Invalid 'name'"
24+
25+
if 'age' in data:
26+
if not isinstance(data['age'], int):
27+
return "Invalid 'age'"
28+
29+
return None # No error
30+
1031
@app.route('/')
1132
def home():
1233
return jsonify({"message": "Flask Student API"}), 200
@@ -21,14 +42,9 @@ def get_students():
2142
@app.route('/students', methods=['POST'])
2243
def add_student():
2344
data = request.get_json()
24-
25-
# Validation
26-
if not data:
27-
return jsonify({"error": "Missing JSON body"}), 400
28-
if 'name' not in data or not isinstance(data['name'], str) or not data['name'].strip():
29-
return jsonify({"error": "Invalid or missing 'name'"}), 400
30-
if 'age' not in data or not isinstance(data['age'], int):
31-
return jsonify({"error": "Invalid or missing 'age'"}), 400
45+
error = validate_student_data(data)
46+
if error:
47+
return jsonify({"error": error}), 400
3248

3349
student = Student(name=data['name'].strip(), age=data['age'])
3450
db.session.add(student)
@@ -39,17 +55,13 @@ def add_student():
3955
def update_student(id):
4056
student = Student.query.get_or_404(id)
4157
data = request.get_json()
58+
error = validate_student_data(data, partial=True)
59+
if error:
60+
return jsonify({"error": error}), 400
4261

43-
# Validation
44-
if not data:
45-
return jsonify({"error": "Missing JSON body"}), 400
4662
if 'name' in data:
47-
if not isinstance(data['name'], str) or not data['name'].strip():
48-
return jsonify({"error": "Invalid 'name'"}), 400
4963
student.name = data['name'].strip()
5064
if 'age' in data:
51-
if not isinstance(data['age'], int):
52-
return jsonify({"error": "Invalid 'age'"}), 400
5365
student.age = data['age']
5466

5567
db.session.commit()

0 commit comments

Comments
 (0)