Download api/routes.py from Muxperts/Rankmate: direct link, hf CLI and curl.
- Browser
- Download file 8.58 kB
-
https://huggingface.co/spaces/Muxperts/Rankmate/resolve/main/api/routes.py
- Command line
-
hf download hf://spaces/Muxperts/Rankmate/api/routes.py
-
curl -L -o routes.py https://huggingface.co/spaces/Muxperts/Rankmate/resolve/main/api/routes.py
8.58 kB
| from fastapi import APIRouter, HTTPException, Body, Request | |
| from typing import List, Dict, Any | |
| from database import crud | |
| from src.logger import logging # Importing your custom logger | |
| from bson import ObjectId | |
| # Create a FastAPI router | |
| router = APIRouter(prefix="/api/v1", tags=["Database Operations"]) | |
| # ========================================== | |
| # PHASE A: MASTER DATA SETUP ENDPOINTS | |
| # ========================================== | |
| def api_create_school(request: Request, school_data: dict = Body(...)): | |
| user = request.session.get("user") | |
| if not user or user.get("role") != "super_admin": | |
| logging.warning("Unauthorized attempt to create a school.") | |
| raise HTTPException(status_code=403, detail="Not authorized. Super Admin privileges required.") | |
| logging.info("Request received to create a new School.") | |
| try: | |
| school_id = crud.create_school(school_data) | |
| logging.info(f"Success: School created with ID: {school_id}") | |
| return {"status": "success", "message": "School created", "id": school_id} | |
| except Exception as e: | |
| logging.error(f"Error creating School: {e}") | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| def api_get_schools(request: Request): | |
| # FIX: Removed authentication requirement so the public /register page can fetch schools | |
| logging.info("Request received to fetch all schools.") | |
| try: | |
| schools = crud.get_all_schools() | |
| return {"status": "success", "data": schools} | |
| except Exception as e: | |
| logging.error(f"Error fetching schools: {e}") | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| def api_create_department(request: Request, dept_data: dict = Body(...)): | |
| user = request.session.get("user") | |
| if not user or user.get("role") not in ["super_admin", "school_admin"]: | |
| logging.warning("Unauthorized attempt to create a department.") | |
| raise HTTPException(status_code=403, detail="Not authorized. Admin privileges required.") | |
| logging.info("Request received to create a new Department.") | |
| try: | |
| dept_id = crud.create_department(dept_data) | |
| logging.info(f"Success: Department created with ID: {dept_id}") | |
| return {"status": "success", "message": "Department created", "id": dept_id} | |
| except Exception as e: | |
| logging.error(f"Error creating Department: {e}") | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| def api_get_departments(request: Request, udise_number: str): | |
| # FIX: Removed authentication requirement so the public /register page can fetch departments | |
| logging.info(f"Request received to fetch departments for school UDISE: {udise_number}") | |
| try: | |
| departments = crud.get_departments_by_school(udise_number) | |
| return {"status": "success", "data": departments} | |
| except Exception as e: | |
| logging.error(f"Error fetching departments: {e}") | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| # ========================================== | |
| # USER MANAGEMENT ENDPOINTS | |
| # ========================================== | |
| def api_verify_user(request: Request, user_id: str, payload: dict = Body(...)): | |
| user = request.session.get("user") | |
| if not user or user.get("role") not in ["super_admin", "school_admin", "hod"]: | |
| logging.warning(f"Unauthorized attempt to verify user {user_id}.") | |
| raise HTTPException(status_code=403, detail="Not authorized to verify users.") | |
| is_verified = payload.get("is_verified", True) | |
| logging.info(f"Request to update verification for user {user_id} to {is_verified} by {user.get('email')}") | |
| try: | |
| success = crud.update_user_verification(user_id, is_verified) | |
| if success: | |
| logging.info(f"User {user_id} verification successfully set to {is_verified}") | |
| return {"status": "success", "message": f"User verification set to {is_verified}"} | |
| else: | |
| logging.warning(f"Verification Failed: User {user_id} not found in database.") | |
| raise HTTPException(status_code=404, detail="User not found") | |
| except Exception as e: | |
| logging.error(f"Error verifying user: {e}") | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| def api_delete_user(request: Request, user_id: str): | |
| user = request.session.get("user") | |
| if not user or user.get("role") not in ["super_admin", "school_admin"]: | |
| logging.warning(f"Unauthorized attempt to delete user {user_id}.") | |
| raise HTTPException(status_code=403, detail="Not authorized to delete users.") | |
| logging.info(f"Request to delete user {user_id} by {user.get('email')}") | |
| try: | |
| success = crud.delete_user(user_id) | |
| if success: | |
| logging.info(f"User {user_id} deleted successfully.") | |
| return {"status": "success", "message": "User deleted successfully"} | |
| else: | |
| logging.warning(f"Deletion Failed: User {user_id} not found in database.") | |
| raise HTTPException(status_code=404, detail="User not found") | |
| except Exception as e: | |
| logging.error(f"Error deleting user: {e}") | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| # ========================================== | |
| # PHASE C: DYNAMIC DASHBOARD DROPDOWNS | |
| # ========================================== | |
| def api_get_classes_for_year(request: Request, academic_year: str): | |
| """Fetches classes for the cascading dropdown based on academic year.""" | |
| user = request.session.get("user") | |
| if not user: | |
| raise HTTPException(status_code=401, detail="Unauthorized") | |
| school_id = user.get("school_id") | |
| dept_id = user.get("department_id") | |
| logging.info(f"API Request: Fetch classes | Year: {academic_year} | School: {school_id} | Dept: {dept_id} | User: {user.get('name')}") | |
| db = crud.get_db() | |
| query = { | |
| "school_id": school_id, | |
| "academic_year": academic_year | |
| } | |
| if dept_id: | |
| query["department_id"] = ObjectId(dept_id) | |
| try: | |
| classes = list(db.classes.find(query, {"name": 1, "_id": 1})) | |
| # Convert ObjectId to string for JSON serialization | |
| for c in classes: | |
| c["_id"] = str(c["_id"]) | |
| logging.info(f"Successfully fetched {len(classes)} classes for year {academic_year}.") | |
| return classes | |
| except Exception as e: | |
| logging.error(f"Error fetching classes (Year: {academic_year}, School: {school_id}, Dept: {dept_id}): {str(e)}") | |
| raise HTTPException(status_code=500, detail="Database error") | |
| def api_get_subjects_for_class(request: Request, class_id: str, semester: str = None): | |
| """Fetches subjects taught to a specific class for the cascading dropdown, dynamically checking actual records.""" | |
| user = request.session.get("user") | |
| if not user: | |
| raise HTTPException(status_code=401, detail="Unauthorized") | |
| school_id = user.get("school_id") | |
| logging.info(f"API Request: Fetch subjects | Class ID: {class_id} | Semester: {semester} | School: {school_id} | User: {user.get('name')}") | |
| db = crud.get_db() | |
| try: | |
| match_q = { | |
| "school_id": school_id, | |
| "class_id": ObjectId(class_id) | |
| } | |
| if semester and semester != 'overall' and semester.isdigit(): | |
| match_q["semester"] = int(semester) | |
| # Aggregate to find exactly what subjects are present in the fact table for this cohort | |
| pipeline = [ | |
| {"$match": match_q}, | |
| {"$group": { | |
| "_id": "$subject_code", | |
| "name": {"$first": "$subject_name"}, | |
| "code": {"$first": "$subject_code"} | |
| }}, | |
| {"$project": {"_id": 0, "code": 1, "name": 1}} | |
| ] | |
| subjects = list(db.academic_records.aggregate(pipeline)) | |
| logging.info(f"Successfully fetched {len(subjects)} dynamic subjects for Class ID: {class_id}.") | |
| return subjects | |
| except Exception as e: | |
| logging.error(f"Error fetching dynamic subjects (Class ID: {class_id}, School: {school_id}): {str(e)}") | |
| raise HTTPException(status_code=500, detail="Database error") |