-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrest.py
More file actions
68 lines (57 loc) · 2.07 KB
/
rest.py
File metadata and controls
68 lines (57 loc) · 2.07 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
from flask import Flask
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
# STUDENTS = {}
STUDENTS = {
'1': {'name': 'Mark', 'age': 23, 'spec': 'math'},
'2': {'name': 'Jane', 'age': 20, 'spec': 'biology'},
'3': {'name': 'Peter', 'age': 21, 'spec': 'history'},
'4': {'name': 'Kate', 'age': 22, 'spec': 'science'},
}
parser = reqparse.RequestParser()
class StudentsList(Resource):
def get(self):
return STUDENTS
def post(self):
parser.add_argument("name")
parser.add_argument("age")
parser.add_argument("spec")
args = parser.parse_args()
student_id = int(max(STUDENTS.keys())) + 1
student_id = '%i' % student_id
STUDENTS[student_id] = {
"name": args["name"],
"age": args["age"],
"spec": args["spec"],
}
return STUDENTS[student_id], 201
class Student(Resource):
def get(self, student_id):
if student_id not in STUDENTS:
return "Not found", 404
else:
return STUDENTS[student_id]
def put(self, student_id):
parser.add_argument("name")
parser.add_argument("age")
parser.add_argument("spec")
args = parser.parse_args()
if student_id not in STUDENTS:
return "Record not found", 404
else:
student = STUDENTS[student_id]
student["name"] = args["name"] if args["name"] is not None else student["name"]
student["age"] = args["age"] if args["age"] is not None else student["age"]
student["spec"] = args["spec"] if args["spec"] is not None else student["spec"]
return student, 200
def delete(self, student_id):
if student_id not in STUDENTS:
return "Not found", 404
else:
del STUDENTS[student_id]
return '', 204
api.add_resource(StudentsList, '/students/')
api.add_resource(Student, '/students/<student_id>')
if __name__ == "__main__":
app.run(debug=True)