Skip to content

Commit 99dae2a

Browse files
eatulrajputAtul Rajput
authored andcommitted
Add Validation check
Signed-off-by: Atul Rajput <[email protected]>
1 parent 690b2d9 commit 99dae2a

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

flask-sqlite/app.py

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from flask import Flask, request, jsonify
22
from models import db, Student
33

4-
54
app = Flask(__name__)
65
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///students.db'
76
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
@@ -22,7 +21,16 @@ def get_students():
2221
@app.route('/students', methods=['POST'])
2322
def add_student():
2423
data = request.get_json()
25-
student = Student(name=data['name'], age=data['age'])
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
32+
33+
student = Student(name=data['name'].strip(), age=data['age'])
2634
db.session.add(student)
2735
db.session.commit()
2836
return jsonify({"id": student.id}), 201
@@ -31,8 +39,19 @@ def add_student():
3139
def update_student(id):
3240
student = Student.query.get_or_404(id)
3341
data = request.get_json()
34-
student.name = data['name']
35-
student.age = data['age']
42+
43+
# Validation
44+
if not data:
45+
return jsonify({"error": "Missing JSON body"}), 400
46+
if 'name' in data:
47+
if not isinstance(data['name'], str) or not data['name'].strip():
48+
return jsonify({"error": "Invalid 'name'"}), 400
49+
student.name = data['name'].strip()
50+
if 'age' in data:
51+
if not isinstance(data['age'], int):
52+
return jsonify({"error": "Invalid 'age'"}), 400
53+
student.age = data['age']
54+
3655
db.session.commit()
3756
return jsonify({"message": "Updated"}), 200
3857

@@ -47,4 +66,3 @@ def delete_student(id):
4766
with app.app_context():
4867
db.create_all()
4968
app.run(debug=True)
50-

0 commit comments

Comments
 (0)