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