Spaces:
Runtime error
Runtime error
FEAT:Updated Main.py file
Browse files
main.py
CHANGED
|
@@ -1,109 +1,100 @@
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
from datetime import datetime
|
| 4 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
import uvicorn
|
| 6 |
from contextlib import asynccontextmanager
|
| 7 |
|
| 8 |
-
|
| 9 |
-
from src.database import create_db_and_tables
|
|
|
|
| 10 |
from src.routers import students, devices, clearance, token, users, admin
|
| 11 |
|
| 12 |
@asynccontextmanager
|
| 13 |
async def lifespan(app_instance: FastAPI):
|
| 14 |
-
"""
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
create_db_and_tables()
|
| 17 |
-
print("Database tables checked/created.")
|
| 18 |
yield
|
| 19 |
-
print("Application shutdown
|
| 20 |
|
| 21 |
|
| 22 |
-
# FastAPI
|
| 23 |
app = FastAPI(
|
| 24 |
title="Undergraduate Clearance System API",
|
| 25 |
description="""
|
| 26 |
A comprehensive API for managing student clearance processes with RFID authentication.
|
| 27 |
|
| 28 |
## Features
|
| 29 |
-
* RFID Authentication
|
| 30 |
-
* Multi-Department Clearance
|
| 31 |
-
* Device Management
|
| 32 |
-
* Role-Based Access
|
| 33 |
-
* Real-Time Tracking
|
| 34 |
|
| 35 |
## Authentication Methods
|
| 36 |
-
* JWT Tokens
|
| 37 |
-
* RFID Tags
|
| 38 |
-
* Device API Keys
|
| 39 |
""",
|
| 40 |
-
version="2.0.
|
| 41 |
lifespan=lifespan,
|
| 42 |
docs_url="/docs",
|
| 43 |
redoc_url="/redoc",
|
| 44 |
openapi_url="/openapi.json",
|
| 45 |
-
|
| 46 |
|
|
|
|
|
|
|
| 47 |
app.add_middleware(
|
| 48 |
CORSMiddleware,
|
| 49 |
-
allow_origins=
|
| 50 |
allow_credentials=True,
|
| 51 |
-
allow_methods=["*"],
|
| 52 |
-
allow_headers=["*"],
|
| 53 |
)
|
| 54 |
|
| 55 |
-
# Include routers
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
app.include_router(devices.router)
|
| 57 |
app.include_router(students.router)
|
| 58 |
-
app.include_router(clearance.router)
|
| 59 |
app.include_router(token.router)
|
| 60 |
app.include_router(users.router)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
# Root endpoint
|
| 64 |
-
@app.get("/", summary="Root endpoint", tags=["Default"])
|
| 65 |
-
async def read_root():
|
| 66 |
-
"""Basic root endpoint to confirm the API is running."""
|
| 67 |
-
return {"message": "Undergraduate Clearance System API is running"}
|
| 68 |
|
|
|
|
| 69 |
|
| 70 |
-
@app.get("/
|
| 71 |
-
async def
|
| 72 |
-
"""
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
"features": [
|
| 77 |
-
"RFID Authentication",
|
| 78 |
-
"Multi-Department Clearance",
|
| 79 |
-
"Device Management",
|
| 80 |
-
"Real-Time Tracking",
|
| 81 |
-
"Comprehensive Logging"
|
| 82 |
-
],
|
| 83 |
-
"supported_authentication": [
|
| 84 |
-
"JWT Tokens",
|
| 85 |
-
"RFID Tags",
|
| 86 |
-
"Device API Keys"
|
| 87 |
-
]
|
| 88 |
-
}
|
| 89 |
|
| 90 |
-
# Health check endpoints
|
| 91 |
@app.get("/health", summary="Health Check", tags=["System"])
|
| 92 |
async def health_check():
|
| 93 |
-
"""
|
|
|
|
|
|
|
| 94 |
health_status = {
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
status_code=status_code,
|
| 104 |
-
content=health_status
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
# Run the FastAPI app using Uvicorn
|
| 108 |
if __name__ == "__main__":
|
|
|
|
| 109 |
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI
|
| 2 |
from fastapi.responses import JSONResponse
|
| 3 |
from datetime import datetime
|
| 4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
import uvicorn
|
| 6 |
from contextlib import asynccontextmanager
|
| 7 |
|
| 8 |
+
# Correctly import the database table creation function
|
| 9 |
+
from src.database import create_db_and_tables
|
| 10 |
+
# Import all the necessary routers for the application
|
| 11 |
from src.routers import students, devices, clearance, token, users, admin
|
| 12 |
|
| 13 |
@asynccontextmanager
|
| 14 |
async def lifespan(app_instance: FastAPI):
|
| 15 |
+
"""
|
| 16 |
+
Handles application startup and shutdown events.
|
| 17 |
+
- On startup, it ensures that all necessary database tables are created.
|
| 18 |
+
- On shutdown, it can be used for cleanup tasks.
|
| 19 |
+
"""
|
| 20 |
+
print("Application startup: Initializing...")
|
| 21 |
+
# Correctly call the function to create database tables
|
| 22 |
create_db_and_tables()
|
| 23 |
+
print("Application startup: Database tables checked/created.")
|
| 24 |
yield
|
| 25 |
+
print("Application shutdown: Cleaning up.")
|
| 26 |
|
| 27 |
|
| 28 |
+
# Initialize the FastAPI application instance with metadata for documentation
|
| 29 |
app = FastAPI(
|
| 30 |
title="Undergraduate Clearance System API",
|
| 31 |
description="""
|
| 32 |
A comprehensive API for managing student clearance processes with RFID authentication.
|
| 33 |
|
| 34 |
## Features
|
| 35 |
+
* **RFID Authentication**: Students and staff use RFID tags for quick access.
|
| 36 |
+
* **Multi-Department Clearance**: Support for Library, Bursary, Alumni, and Departmental clearances.
|
| 37 |
+
* **Device Management**: Secure management of ESP32 RFID readers via API keys.
|
| 38 |
+
* **Role-Based Access Control**: Differentiated permissions for Students, Staff, and Administrators.
|
| 39 |
+
* **Real-Time Tracking**: Live updates on clearance status with comprehensive logging.
|
| 40 |
|
| 41 |
## Authentication Methods
|
| 42 |
+
* **JWT Tokens**: For web interfaces and administrative API access.
|
| 43 |
+
* **RFID Tags**: For quick, on-premise authentication of students and staff.
|
| 44 |
+
* **Device API Keys**: For secure communication with hardware like ESP32 RFID readers.
|
| 45 |
""",
|
| 46 |
+
version="2.0.1",
|
| 47 |
lifespan=lifespan,
|
| 48 |
docs_url="/docs",
|
| 49 |
redoc_url="/redoc",
|
| 50 |
openapi_url="/openapi.json",
|
| 51 |
+
)
|
| 52 |
|
| 53 |
+
# Configure CORS (Cross-Origin Resource Sharing) middleware
|
| 54 |
+
# This allows the frontend (like the Streamlit app) to communicate with the API
|
| 55 |
app.add_middleware(
|
| 56 |
CORSMiddleware,
|
| 57 |
+
allow_origins=['*'], # Allows all origins, consider restricting in production
|
| 58 |
allow_credentials=True,
|
| 59 |
+
allow_methods=["*"], # Allows all HTTP methods
|
| 60 |
+
allow_headers=["*"], # Allows all headers
|
| 61 |
)
|
| 62 |
|
| 63 |
+
# Include all the API routers into the main application
|
| 64 |
+
# Each router handles a specific domain of the application (e.g., students, devices)
|
| 65 |
+
print("Including API routers...")
|
| 66 |
+
app.include_router(admin.router)
|
| 67 |
+
app.include_router(clearance.router)
|
| 68 |
app.include_router(devices.router)
|
| 69 |
app.include_router(students.router)
|
|
|
|
| 70 |
app.include_router(token.router)
|
| 71 |
app.include_router(users.router)
|
| 72 |
+
print("All API routers included.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
+
# --- Default and System Endpoints ---
|
| 75 |
|
| 76 |
+
@app.get("/", summary="Root Endpoint", tags=["System"])
|
| 77 |
+
async def read_root():
|
| 78 |
+
"""
|
| 79 |
+
A simple root endpoint to confirm that the API is running and accessible.
|
| 80 |
+
"""
|
| 81 |
+
return {"message": "Welcome to the Undergraduate Clearance System API. See /docs for details."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
|
|
|
| 83 |
@app.get("/health", summary="Health Check", tags=["System"])
|
| 84 |
async def health_check():
|
| 85 |
+
"""
|
| 86 |
+
Provides a health status check for the API, useful for monitoring and uptime checks.
|
| 87 |
+
"""
|
| 88 |
health_status = {
|
| 89 |
+
"status": "healthy",
|
| 90 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 91 |
+
"version": app.version,
|
| 92 |
+
}
|
| 93 |
+
return JSONResponse(status_code=200, content=health_status)
|
| 94 |
+
|
| 95 |
+
# This block allows the script to be run directly using `python main.py`
|
| 96 |
+
# It will start the Uvicorn server, which is ideal for development.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
if __name__ == "__main__":
|
| 98 |
+
print("Starting Uvicorn server for development...")
|
| 99 |
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
| 100 |
+
|