Update generated backend for task_management

This commit is contained in:
Idris Abdurrahman 2025-03-20 13:05:13 +01:00
parent 6f500e5001
commit 82a6805af1
15 changed files with 217 additions and 8 deletions

View File

@ -0,0 +1,8 @@
from app.api.db.database import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

View File

@ -0,0 +1,16 @@
import time
from starlette.middleware.base import BaseHTTPMiddleware
from loguru import logger
class ActivityTrackerMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
start_time = time.time()
method = request.method
url = str(request.url)
response = await call_next(request)
process_time = time.time() - start_time
logger.info(f"{method} {url} - {process_time:.6f} seconds")
return response

11
app/api/db/database.py Normal file
View File

@ -0,0 +1,11 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./task_management.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

13
app/api/v1/models/and.py Normal file
View File

@ -0,0 +1,13 @@
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from app.api.db.database import Base
class And(Base):
__tablename__ = "ands"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
task_id = Column(Integer, ForeignKey("tasks.id"))
task = relationship("Task", back_populates="ands")

View File

@ -0,0 +1,9 @@
from sqlalchemy import Column, Integer, String
from app.api.db.database import Base
class Teams(Base):
__tablename__ = "teams"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, unique=True, index=True)
description = Column(String)

12
app/api/v1/models/user.py Normal file
View File

@ -0,0 +1,12 @@
from sqlalchemy import Column, Integer, String, Boolean
from app.api.db.database import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
email = Column(String, unique=True, index=True)
password = Column(String)
is_active = Column(Boolean, default=True)
is_admin = Column(Boolean, default=False)

View File

@ -0,0 +1,9 @@
from fastapi import APIRouter
from .teams import router as teams_router
from .user import router as user_router
router = APIRouter()
router.include_router(teams_router, prefix="/teams", tags=["teams"])
router.include_router(user_router, prefix="/users", tags=["users"])

28
app/api/v1/routes/and.py Normal file
View File

@ -0,0 +1,28 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.v1.models.and import And
from app.api.v1.schemas.and import AndCreate, AndOut
from app.api.core.dependencies.dependencies import get_db
router = APIRouter()
@router.get("/ands", response_model=list[AndOut])
def read_ands(db: Session = Depends(get_db)):
ands = db.query(And).all()
return ands
@router.post("/ands", response_model=AndOut)
def create_and(and_in: AndCreate, db: Session = Depends(get_db)):
and_data = And(**and_in.dict())
db.add(and_data)
db.commit()
db.refresh(and_data)
return and_data
@router.get("/ands/{id}", response_model=AndOut)
def read_and(id: int, db: Session = Depends(get_db)):
and_data = db.query(And).get(id)
if not and_data:
raise HTTPException(status_code=404, detail="And not found")
return and_data

View File

@ -0,0 +1,28 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.v1.models.teams import Teams
from app.api.v1.schemas.teams import TeamsCreate, TeamsResponse
from app.api.core.dependencies.dependencies import get_db
router = APIRouter()
@router.get("/teamss", response_model=List[TeamsResponse])
def read_teamss(db: Session = Depends(get_db)):
return db.query(Teams).all()
@router.post("/teamss", response_model=TeamsResponse)
def create_teams(teams: TeamsCreate, db: Session = Depends(get_db)):
db_teams = Teams(**teams.dict())
db.add(db_teams)
db.commit()
db.refresh(db_teams)
return db_teams
@router.get("/teamss/{id}", response_model=TeamsResponse)
def read_teams(id: int, db: Session = Depends(get_db)):
db_teams = db.query(Teams).get(id)
if not db_teams:
raise HTTPException(status_code=404, detail="Teams not found")
return db_teams

29
app/api/v1/routes/user.py Normal file
View File

@ -0,0 +1,29 @@
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.v1.models.user import User
from app.api.v1.schemas.user import UserCreate, UserResponse
from app.api.core.dependencies.dependencies import get_db
router = APIRouter()
@router.get("/users", response_model=List[UserResponse])
def read_users(db: Session = Depends(get_db)):
users = db.query(User).all()
return users
@router.post("/users", response_model=UserResponse)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = User(**user.dict())
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@router.get("/users/{user_id}", response_model=UserResponse)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = db.query(User).filter(User.id == user_id).first()
if not db_user:
raise HTTPException(status_code=404, detail="User not found")
return db_user

13
app/api/v1/schemas/and.py Normal file
View File

@ -0,0 +1,13 @@
from pydantic import BaseModel
class AndBase(BaseModel):
pass
class AndCreate(AndBase):
pass
class And(AndBase):
id: int
class Config:
orm_mode = True

View File

@ -0,0 +1,13 @@
from pydantic import BaseModel
class TeamsCreate(BaseModel):
name: str
description: str | None = None
class Teams(BaseModel):
id: int
name: str
description: str | None = None
class Config:
orm_mode = True

View File

@ -0,0 +1,18 @@
from typing import Optional
from pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
email: Optional[EmailStr] = None
is_active: Optional[bool] = True
is_superuser: bool = False
full_name: Optional[str] = None
class UserCreate(UserBase):
email: EmailStr
password: str
class User(UserBase):
id: int
class Config:
orm_mode = True

13
main.py
View File

@ -1,7 +1,12 @@
from fastapi import FastAPI
from app.api.db.database import engine, Base
from app.api.v1.routes import router as v1_router
from app.api.core.middleware.activity_tracker import ActivityTrackerMiddleware
app = FastAPI(title="Generated Backend")
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Welcome to the generated backend"}
Base.metadata.create_all(bind=engine)
app.include_router(v1_router, prefix="/v1")
app.add_middleware(ActivityTrackerMiddleware)

View File

@ -1,4 +1 @@
fastapi
uvicorn
sqlalchemy
pydantic
# No valid code generated