File size: 2,203 Bytes
cb7f5fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f63e73c
 
cb7f5fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Body, status
from fastapi.encoders import jsonable_encoder
from models.schema import (
    StudentSchema,
    StudentUpdateSchema,
    ResponseModel,
    ErrorResponseModel,
)

from database import *

router = APIRouter()


@router.post("/", response_description="Student data added into the database")
async def add_student_data(student: StudentSchema = Body(...)):
    student = jsonable_encoder(student)

    # if get_student_data(student["pin"]):
    #     return ErrorResponseModel("Student Exist", 404, f"Student with PIN: {student['pin']} already exists.")

    new_student = await add(student)
    return ResponseModel(new_student, "Student added successfully.")


@router.get("/all", response_description="Students Data Retrieved")
async def get_all_students():
    students = await get_all()
    if len(students) < 1:
        return ErrorResponseModel("Empty Database", 404, "No Students data found")

    if students:
        return ResponseModel(students, "Retrieved all students data")
    ErrorResponseModel("An Error Occurred", 404, "No Students database found")


@router.get("/{pin}", response_description="Student data retrieved")
async def get_student_data(pin):
    student = await get(pin)
    if student:
        return ResponseModel(student, "Student data retrieved successfully")
    return ErrorResponseModel("An error occurred.", 404, "Student doesn't exist.")


@router.put("/{pin}")
async def update_student_data(pin: str, data: StudentUpdateSchema = Body(...)):
    data = {k: v for k, v in data.dict().items() if v is not None}
    updated_student = await update(pin, data)
    if updated_student:
        return ResponseModel(updated_student, f"{pin} data updated")
    return ErrorResponseModel("An Error occurred", 404, "Cannot update the data. Maybe pin doesn't exist")


@router.delete("/delete/{pin}", response_description="Delete student from database")
async def delete_student(pin: str):
    student = await delete(pin)
    if student:
        return ResponseModel(f"Student with {pin} removed from the database", "Operation Success")
    return ErrorResponseModel("An Error occurred", 404, f"student with PIN {pin} does not exist")