refactor(backend): improve CRUD with Depends, status codes, and env DB support

This commit is contained in:
Damir
2026-04-07 21:55:17 +03:00
parent 600c75beb3
commit 4505b9f0e2

View File

@@ -1,13 +1,16 @@
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, Depends, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from typing import List, Optional
from contextlib import asynccontextmanager
import os
# Database setup
SQLALCHEMY_DATABASE_URL = "sqlite:///./team_status.db"
SQLALCHEMY_DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./team_status.db")
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
@@ -73,59 +76,43 @@ def get_db():
# CRUD Operations
@app.get("/api/employees", response_model=List[EmployeeResponse])
def read_employees():
def read_employees(db: Session = Depends(get_db)):
"""Get all employees"""
db = SessionLocal()
try:
employees = db.query(Employee).all()
return employees
finally:
db.close()
@app.post("/api/employees", response_model=EmployeeResponse)
def create_employee(employee: EmployeeCreate):
@app.post("/api/employees", response_model=EmployeeResponse, status_code=status.HTTP_201_CREATED)
def create_employee(employee: EmployeeCreate, db: Session = Depends(get_db)):
"""Create a new employee"""
db = SessionLocal()
try:
db_employee = Employee(**employee.model_dump(), status="Online")
db.add(db_employee)
db.commit()
db.refresh(db_employee)
return db_employee
finally:
db.close()
@app.put("/api/employees/{employee_id}/status", response_model=EmployeeResponse)
def update_employee_status(employee_id: int, status_update: StatusUpdate):
def update_employee_status(employee_id: int, status_update: StatusUpdate, db: Session = Depends(get_db)):
"""Update employee status"""
db = SessionLocal()
try:
employee = db.query(Employee).filter(Employee.id == employee_id).first()
if not employee:
raise HTTPException(status_code=404, detail="Employee not found")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Employee not found")
employee.status = status_update.status
db.commit()
db.refresh(employee)
return employee
finally:
db.close()
@app.delete("/api/employees/{employee_id}")
def delete_employee(employee_id: int):
@app.delete("/api/employees/{employee_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_employee(employee_id: int, db: Session = Depends(get_db)):
"""Delete an employee"""
db = SessionLocal()
try:
employee = db.query(Employee).filter(Employee.id == employee_id).first()
if not employee:
raise HTTPException(status_code=404, detail="Employee not found")
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Employee not found")
db.delete(employee)
db.commit()
return {"message": "Employee deleted successfully"}
finally:
db.close()
return None
if __name__ == "__main__":