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()
try:
employees = db.query(Employee).all() employees = db.query(Employee).all()
return employees 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()
try:
db_employee = Employee(**employee.model_dump(), status="Online") db_employee = Employee(**employee.model_dump(), status="Online")
db.add(db_employee) db.add(db_employee)
db.commit() db.commit()
db.refresh(db_employee) db.refresh(db_employee)
return 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()
try:
employee = db.query(Employee).filter(Employee.id == employee_id).first() employee = db.query(Employee).filter(Employee.id == employee_id).first()
if not employee: 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 employee.status = status_update.status
db.commit() db.commit()
db.refresh(employee) db.refresh(employee)
return 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()
try:
employee = db.query(Employee).filter(Employee.id == employee_id).first() employee = db.query(Employee).filter(Employee.id == employee_id).first()
if not employee: 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.delete(employee)
db.commit() db.commit()
return {"message": "Employee deleted successfully"} return None
finally:
db.close()
if __name__ == "__main__": if __name__ == "__main__":