Skip to content

Commit 61c4edd

Browse files
author
Uttam Singh
committed
Enhanced main.py with forgot-password OTP and auto DB creation
1 parent 7a0a234 commit 61c4edd

File tree

1 file changed

+38
-45
lines changed

1 file changed

+38
-45
lines changed

backend/app/main.py

Lines changed: 38 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,25 @@
1-
from fastapi import FastAPI, UploadFile, File, Depends, HTTPException, Form
1+
from fastapi import FastAPI, UploadFile, File, Depends, HTTPException
22
from fastapi.middleware.cors import CORSMiddleware
33
from sqlalchemy import create_engine, Column, Integer, String, Date, Text
44
from sqlalchemy.orm import sessionmaker, declarative_base, Session
5-
from pydantic import BaseModel
65
from datetime import date
7-
import os, shutil
86
from dotenv import load_dotenv
7+
from pydantic import BaseModel
8+
import os, shutil
99

10-
# ==============================
11-
# 1️⃣ Load environment variables
12-
# ==============================
10+
# ================================================
11+
# 1️⃣ Load Environment Variables & Database Setup
12+
# ================================================
1313
load_dotenv()
1414

1515
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./app.db")
1616
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
1717
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
1818
Base = declarative_base()
1919

20-
21-
# ==============================
22-
# 2️⃣ Database models (Tasks, Audit Logs)
23-
# ==============================
20+
# ================================================
21+
# 2️⃣ Local Models for Internal Tables (Task + Audit Log)
22+
# ================================================
2423
class Task(Base):
2524
__tablename__ = "tasks"
2625
id = Column(Integer, primary_key=True, index=True)
@@ -41,16 +40,12 @@ class AuditLog(Base):
4140
detail = Column(Text)
4241

4342

44-
# ✅ Create all tables initially (will also be re-created by /create-db)
45-
Base.metadata.create_all(bind=engine)
46-
47-
48-
# ==============================
49-
# 3️⃣ FastAPI app setup
50-
# ==============================
43+
# ================================================
44+
# 3️⃣ FastAPI App Initialization
45+
# ================================================
5146
app = FastAPI(title="FAT-EIBL (Edme) – API")
5247

53-
# Enable CORS for frontend
48+
# Enable CORS for the frontend
5449
allow = os.getenv("ALLOW_ORIGINS", "*").split(",")
5550
app.add_middleware(
5651
CORSMiddleware,
@@ -60,44 +55,41 @@ class AuditLog(Base):
6055
allow_headers=["*"],
6156
)
6257

63-
64-
# ==============================
65-
# 4️⃣ Database dependency
66-
# ==============================
58+
# ================================================
59+
# 4️⃣ Database Dependency
60+
# ================================================
6761
def get_db():
6862
db = SessionLocal()
6963
try:
7064
yield db
7165
finally:
7266
db.close()
7367

74-
75-
# ==============================
76-
# 5️⃣ Import Routers (User + Forgot Password)
77-
# ==============================
68+
# ================================================
69+
# 5️⃣ Import Routers (Users, Forgot Password)
70+
# ================================================
7871
from app.routers import users, forgot_password
7972

8073
app.include_router(users.router, prefix="/users", tags=["Users"])
8174
app.include_router(forgot_password.router, prefix="/users", tags=["Forgot Password"])
8275

83-
84-
# ==============================
85-
# 6️⃣ Health check
86-
# ==============================
76+
# ================================================
77+
# 6️⃣ Health Check Endpoint
78+
# ================================================
8779
@app.get("/health")
88-
def health():
89-
return {"status": "ok", "message": "Backend is running"}
90-
80+
def health_check():
81+
"""Simple endpoint to verify backend health"""
82+
return {"status": "ok", "message": "Backend is running properly"}
9183

92-
# ==============================
93-
# 7️⃣ File Uploads (optional)
94-
# ==============================
84+
# ================================================
85+
# 7️⃣ File Upload Handler (Optional)
86+
# ================================================
9587
UPLOAD_DIR = os.path.join(os.getcwd(), "uploads")
9688
os.makedirs(UPLOAD_DIR, exist_ok=True)
9789

98-
9990
@app.post("/upload/{task_id}")
10091
async def upload_file(task_id: int, file: UploadFile = File(...), db: Session = Depends(get_db)):
92+
"""Attach a file to a specific task"""
10193
obj = db.get(Task, task_id)
10294
if not obj:
10395
raise HTTPException(status_code=404, detail="Task not found")
@@ -109,26 +101,27 @@ async def upload_file(task_id: int, file: UploadFile = File(...), db: Session =
109101
shutil.copyfileobj(file.file, buffer)
110102

111103
obj.attachment = safe_name
112-
db.add(AuditLog(action="upload", detail=f"Task ID {task_id} file {safe_name}"))
104+
db.add(AuditLog(action="upload", detail=f"Task ID {task_id} uploaded file {safe_name}"))
113105
db.commit()
114106

115107
return {"task_id": task_id, "filename": safe_name}
116108

117-
118-
# ==============================
119-
# 8️⃣ Emergency endpoint: Create database tables
120-
# ==============================
109+
# ================================================
110+
# 8️⃣ Database Initialization Endpoint (/create-db)
111+
# ================================================
121112
from app.models.user import User
113+
from app.models.otp import OtpModel
122114
from app.database import Base as DBBase, engine as DBEngine
123115

124-
125116
@app.get("/create-db")
126117
def create_database():
127118
"""
128-
🔧 Use this endpoint on Render once if tables fail to auto-create.
119+
🔧 Create all database tables if they don't exist.
120+
Run this once on Render or local after migrations.
129121
"""
130122
try:
131123
DBBase.metadata.create_all(bind=DBEngine)
132-
return {"ok": True, "message": "Database tables created successfully"}
124+
Base.metadata.create_all(bind=engine)
125+
return {"ok": True, "message": "✅ All database tables created successfully"}
133126
except Exception as e:
134127
return {"ok": False, "error": str(e)}

0 commit comments

Comments
 (0)