Spaces:
Runtime error
Runtime error
| import motor.motor_asyncio | |
| import os | |
| from bson.objectid import ObjectId | |
| MONGO_DETAILS = os.getenv("MONGO_DETAILS") | |
| client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_DETAILS) | |
| database = client.fastapi_students | |
| students_collection = database.get_collection("students") | |
| # helpers | |
| def student_helper(student) -> dict: | |
| return { | |
| "id": str(student["_id"]), | |
| "name": student["name"], | |
| "email": student["email"], | |
| "password": student["password"], | |
| "year": student["year"], | |
| "branch": student["branch"], | |
| "division": student["division"], | |
| "pin": student["pin"], | |
| "gpa": student["gpa"], | |
| "phone": student["phone"], | |
| "address": student["address"], | |
| } | |
| # Retrieve all students present in the database | |
| async def get_all(): | |
| students = [] | |
| async for student in students_collection.find(): | |
| students.append(student_helper(student)) | |
| return students | |
| async def add(student_data: dict) -> dict: | |
| student = await students_collection.insert_one(student_data) | |
| new_student = await students_collection.find_one({"_id": student.inserted_id}) | |
| return student_helper(new_student) | |
| async def get(PIN: str) -> dict: | |
| student = await students_collection.find_one({"pin": PIN}) | |
| if student: | |
| return student_helper(student) | |
| async def update(PIN: str, updated_data: dict) -> dict: | |
| if not updated_data: | |
| return False | |
| student = await students_collection.find_one({"pin": PIN}) | |
| if student: | |
| students_collection.update_one({"pin": PIN}, {"$set": updated_data}) | |
| return True | |
| return False | |
| async def delete(PIN: str): | |
| student = await students_collection.find_one({"pin": PIN}) | |
| if student: | |
| await students_collection.delete_one({"pin": PIN}) | |
| return True | |
| return False | |