-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathapi.py
More file actions
49 lines (38 loc) · 1.4 KB
/
api.py
File metadata and controls
49 lines (38 loc) · 1.4 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
"""Functions handling API endpoints."""
import database
import models_autogenerated as models
def search():
"""Get all employees from the database."""
employees = models.Employee.query.all()
employee_dicts = map(lambda employee: employee.to_dict(), employees)
return list(employee_dicts)
def post(body):
"""Save an employee to the database."""
if models.Employee.query.filter_by(id=body["id"]).first() is not None:
return ("Employee already exists.", 400)
employee = models.Employee.from_dict(**body)
database.db.session.add(employee)
database.db.session.commit()
def get(id):
"""Get an employee from the database."""
employee = models.Employee.query.filter_by(id=id).first()
if employee is None:
return ("Employee not found.", 404)
return employee.to_dict()
def patch(body, id):
"""Update an employee in the dayabase."""
employee = models.Employee.query.filter_by(id=id).first()
if employee is None:
return ("Employee not found.", 404)
employee.name = body["name"]
employee.division = body["division"]
employee.salary = body["salary"]
database.db.session.commit()
return 200
def delete(id):
"""Delete an employee from the database."""
result = models.Employee.query.filter_by(id=id).delete()
if not result:
return ("Employee not found.", 404)
database.db.session.commit()
return 200