🐛 fix(components.py): change variable name from component to component_model in create_component and update_component functions for better readability

 feat(components.py): add support for `create_at` and `update_at` fields in Component model to track creation and update timestamps
🔥 refactor(components.py): remove unused imports and variables in components.py
🔥 refactor(component.py): remove unused imports and variables in component.py
🔥 refactor(component.py): remove commented out code in component.py
This commit is contained in:
gustavoschaedler 2023-07-12 15:10:37 +01:00
commit 2f4e98477c
2 changed files with 36 additions and 144 deletions

View file

@ -1,30 +1,35 @@
from typing import List
from uuid import UUID
from langflow.database.models.component import Component
from langflow.database.models.component import Component, ComponentModel
from langflow.database.base import get_session
from sqlmodel import Session, select
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.exc import IntegrityError
from datetime import datetime
COMPONENT_NOT_FOUND = "Component not found"
COMPONENT_ALREADY_EXISTS = "A component with the same id already exists."
COMPONENT_DELETED = "Component deleted"
router = APIRouter(prefix="/components", tags=["Components"])
@router.post("/", response_model=Component)
def create_component(component: Component, db: Session = Depends(get_session)):
def create_component(component: ComponentModel, db: Session = Depends(get_session)):
db_component = Component(**component.dict())
try:
db.add(component)
db.add(db_component)
db.commit()
db.refresh(component)
db.refresh(db_component)
except IntegrityError as e:
db.rollback()
raise HTTPException(
status_code=400,
detail="A component with the same id already exists.",
detail=COMPONENT_ALREADY_EXISTS,
) from e
return component
return db_component
@router.get("/{component_id}", response_model=Component)
@ -37,19 +42,25 @@ def read_component(component_id: UUID, db: Session = Depends(get_session)):
@router.get("/", response_model=List[Component])
def read_components(skip: int = 0, limit: int = 50, db: Session = Depends(get_session)):
return db.execute(select(Component).offset(skip).limit(limit)).fetchall()
query = select(Component)
query = query.offset(skip).limit(limit)
return db.execute(query).fetchall()
@router.patch("/{component_id}", response_model=Component)
def update_component(
component_id: UUID, component: Component, db: Session = Depends(get_session)
component_id: UUID, component: ComponentModel, db: Session = Depends(get_session)
):
db_component = db.get(Component, component_id)
if not db_component:
raise HTTPException(status_code=404, detail=COMPONENT_NOT_FOUND)
component_data = component.dict(exclude_unset=True)
for key, value in component_data.items():
setattr(db_component, key, value)
db_component.update_at = datetime.utcnow()
db.commit()
db.refresh(db_component)
return db_component
@ -62,69 +73,4 @@ def delete_component(component_id: UUID, db: Session = Depends(get_session)):
raise HTTPException(status_code=404, detail=COMPONENT_NOT_FOUND)
db.delete(component)
db.commit()
return {"detail": "Component deleted"}
# @router.post("/", response_model=ComponentRead, status_code=201)
# def create(*, session: Session = Depends(get_session), component: ComponentCreate):
# db = Component.from_orm(component)
# session.add(db)
# session.commit()
# session.refresh(db)
# return db
# @router.get("/", response_model=list[ComponentRead], status_code=200)
# def read_all(*, session: Session = Depends(get_session)):
# try:
# sql = select(Component)
# components = session.exec(sql).all()
# except Exception as e:
# raise HTTPException(status_code=500, detail=str(e)) from e
# return [jsonable_encoder(component) for component in components]
# @router.get("/{id}", response_model=ComponentRead, status_code=200)
# def read(*, session: Session = Depends(get_session), id: UUID):
# if component := session.get(Component, id):
# return component
# else:
# raise HTTPException(status_code=404, detail=COMPONENT_NOT_FOUND)
# @router.patch("/{id}", response_model=ComponentRead, status_code=200)
# def update(
# *, session: Session = Depends(get_session), id: UUID, component: ComponentUpdate
# ):
# db = session.get(Component, id)
# if not db:
# raise HTTPException(status_code=404, detail=COMPONENT_NOT_FOUND)
# data = component.dict(exclude_unset=True)
# if settings.remove_api_keys:
# data = remove_api_keys(data)
# for key, value in data.items():
# setattr(db, key, value)
# session.add(db)
# session.commit()
# session.refresh(db)
# return db
# @router.delete("/{id}", status_code=200)
# def delete(*, session: Session = Depends(get_session), id: UUID):
# component = session.get(Component, id)
# if not component:
# raise HTTPException(status_code=404, detail=COMPONENT_NOT_FOUND)
# session.delete(component)
# session.commit()
# return {"message": "Component deleted successfully"}
return {"detail": COMPONENT_DELETED}

View file

@ -1,83 +1,29 @@
from langflow.database.models.base import SQLModelSerializable
from langflow.database.models.base import SQLModelSerializable, SQLModel
from sqlmodel import Field
from typing import Optional
from datetime import datetime
import uuid
# def orjson_dumps(v, *, default):
# # orjson.dumps returns bytes, to match standard json.dumps we need to decode
# return orjson.dumps(v, default=default).decode()
# class SQLModelSerializable(SQLModel):
# class Config:
# orm_mode = True
# json_loads = orjson.loads
# json_dumps = orjson_dumps
# DATABASE_URL = "sqlite+pysqlite:///./database.db"
# engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}, poolclass=StaticPool)
class Component(SQLModelSerializable, table=True):
id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True)
id_frontend_node: uuid.UUID = Field(index=True)
frontend_node_id: uuid.UUID = Field(index=True)
name: str = Field(index=True)
description: Optional[str] = Field(index=True)
code_python: Optional[str] = Field(default=None)
return_type: Optional[str] = Field(index=True)
create_at: datetime = Field(default_factory=datetime.utcnow)
update_at: datetime = Field(default_factory=datetime.utcnow)
description: Optional[str] = Field(default=None)
python_code: Optional[str] = Field(default=None)
return_type: Optional[str] = Field(default=None)
is_disabled: bool = Field(default=False)
is_read_only: bool = Field(default=False)
create_at: datetime = Field(default_factory=datetime.utcnow)
update_at: datetime = Field(default_factory=datetime.utcnow)
# app = FastAPI()
# def get_db():
# with Session(engine) as session:
# yield session
# @app.on_event("startup")
# def on_startup():
# SQLModel.metadata.create_all(engine)
# @app.post("/components/", response_model=Component)
# def create_component(component: Component, db: Session = Depends(get_db)):
# db.add(component)
# db.commit()
# db.refresh(component)
# return component
# @app.get("/components/{component_id}", response_model=Component)
# def read_component(component_id: uuid.UUID, db: Session = Depends(get_db)):
# component = db.get(Component, component_id)
# if not component:
# raise HTTPException(status_code=404, detail="Component not found")
# return component
# @app.get("/components/", response_model=List[Component])
# def read_components(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
# components = db.execute(select(Component).offset(skip).limit(limit)).fetchall()
# return components
# @app.put("/components/{component_id}", response_model=Component)
# def update_component(component_id: uuid.UUID, component: Component, db: Session = Depends(get_db)):
# db_component = db.get(Component, component_id)
# if not db_component:
# raise HTTPException(status_code=404, detail="Component not found")
# component_data = component.dict(exclude_unset=True)
# for key, value in component_data.items():
# setattr(db_component, key, value)
# db.commit()
# db.refresh(db_component)
# return db_component
# @app.delete("/components/{component_id}")
# def delete_component(component_id: uuid.UUID, db: Session = Depends(get_db)):
# component = db.get(Component, component_id)
# if not component:
# raise HTTPException(status_code=404, detail="Component not found")
# db.delete(component)
# db.commit()
# return {"detail": "Component deleted"}
class ComponentModel(SQLModel):
id: uuid.UUID = Field(default_factory=uuid.uuid4)
frontend_node_id: uuid.UUID = Field(default=uuid.uuid4())
name: str = Field(default="")
description: Optional[str] = None
python_code: Optional[str] = None
return_type: Optional[str] = None
is_disabled: bool = False
is_read_only: bool = False