diff --git a/collectionObj/models.py b/collectionObj/models.py index ef6c257..5ddc1d7 100644 --- a/collectionObj/models.py +++ b/collectionObj/models.py @@ -1,22 +1,43 @@ -from fastapi import HTTPException -from sqlalchemy import Column, Integer, String, Float, Boolean, ForeignKey -from sqlalchemy.dialects.postgresql import ARRAY +from fastapi import HTTPException, Depends +from sqlalchemy import Integer, String, Boolean +from pydantic import BaseModel from sqlalchemy.orm import Session, relationship, mapped_column, Mapped from ..config import Base, get_session_db, user_collection, collection_item +from ..auth.models import DBUser from typing import TYPE_CHECKING if TYPE_CHECKING: - from ..auth.models import DBUser - from ..items.models import Items + from ..items.models import Items, Item + + +###### SCHEMAS ######### +class CollectionBase(BaseModel): + collection_name : str | None = None + collection_description : str | None = None + visibility : bool | None = None + +class CollectionCreate(CollectionBase): + pass + +class CollectionPublic(CollectionBase): + collection_id : int | None = None + + class Config: + from_attributes = True #sqlalchemy ile pydantic arasında geçiş yapabilmek için kullanılır + +class CollectionUpdate(CollectionBase): + pass + + ##### veri tabanı modelleri ##### class CollectionsDB(Base): __tablename__ = "collections_table" - collection_id : Mapped[int] = mapped_column(Integer, primary_key=True) + collection_id : Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True) #user_id : Mapped[int] = mapped_column(Integer, ForeignKey("users_table.user_id"), nullable=False) # user_id ile ilişki #item_id : Mapped[list[int]] = mapped_column(Integer, ForeignKey("items_table.item_id"), nullable=False) # item_id ile ilişki visibility : Mapped[bool] = mapped_column(Boolean, default=True) @@ -24,7 +45,7 @@ class CollectionsDB(Base): collection_description : Mapped[str] = mapped_column(String, default="No description") # ilişkiler - users : Mapped['DBUser'] = relationship( + users : Mapped[list['DBUser']] = relationship( "DBUser", secondary=user_collection, back_populates="collections", @@ -39,4 +60,114 @@ class CollectionsDB(Base): ) - #### collection bir item listesi birde kullanıcı listesi tutacak \ No newline at end of file + #### collection bir item listesi birde kullanıcı listesi tutacak + + + +def create_colletion( + collection: CollectionCreate | None = None, + user_id : int | None = None + +) -> bool: + """ + Collection oluşturma fonksiyonu + """ + if collection is None: + raise HTTPException(status_code=400, detail="Collection is None returned") + + session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın + user = session.query(DBUser).filter(DBUser.user_id == user_id).first() + if user is None: + raise HTTPException(status_code=404, detail="User not found") + + + try: + new_collection = CollectionsDB( + collection_name=collection.collection_name, + collection_description=collection.collection_description, + visibility=collection.visibility + ) + + new_collection.users.append(user) + session.add(new_collection) + session.commit() + except Exception as e: + raise HTTPException(status_code=500, detail=f"Error creating collection: {e}") + + return True + + +def get_collections( + user_id : int | None = None +) -> list[CollectionPublic] | None: + """ + Kullanıcının collectionlarını döndürür + """ + if user_id is None: + raise HTTPException(status_code=400, detail="User id is None") + + session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın + collections = session.query(CollectionsDB).filter(CollectionsDB.users.any(user_id=user_id)).all() + + if collections is None: + raise HTTPException(status_code=404, detail="No collections found") + + return collections + +def update_collection( + collection: CollectionUpdate | None = None, + user_id : int | None = None, + collection_id : int | None = None +) -> bool: + """ + Collection güncelleme fonksiyonu + """ + if collection is None: + raise HTTPException(status_code=400, detail="Collection is None returned") + + session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın + user = session.query(DBUser).filter(DBUser.user_id == user_id).first() + if user is None: + raise HTTPException(status_code=404, detail="User not found") + + collection_to_update = session.query(CollectionsDB).filter(CollectionsDB.collection_id == collection_id).first() + if collection_to_update is None: + raise HTTPException(status_code=404, detail="Collection not found") + + try: + collection_to_update.collection_name = collection.collection_name + collection_to_update.collection_description = collection.collection_description + collection_to_update.visibility = collection.visibility + + session.commit() + except Exception as e: + raise HTTPException(status_code=500, detail=f"Error updating collection: {e}") + + return True + +def delete_collection( + user_id : int | None = None, + collection_id : int | None = None +) -> bool: + """ + Collection silme fonksiyonu + """ + if user_id is None or collection_id is None: + raise HTTPException(status_code=400, detail="User id or collection id is None") + + session = next(get_session_db()) # -> get_session_db() fonksiyonu daima generator döndürür next ile çağırmalısın + user = session.query(DBUser).filter(DBUser.user_id == user_id).first() + if user is None: + raise HTTPException(status_code=404, detail="User not found") + + collection_to_delete = session.query(CollectionsDB).filter(CollectionsDB.collection_id == collection_id).first() + if collection_to_delete is None: + raise HTTPException(status_code=404, detail="Collection not found") + + try: + session.delete(collection_to_delete) + session.commit() + except Exception as e: + raise HTTPException(status_code=500, detail=f"Error deleting collection: {e}") + + return True \ No newline at end of file diff --git a/collectionObj/router.py b/collectionObj/router.py index 72387ea..f258273 100644 --- a/collectionObj/router.py +++ b/collectionObj/router.py @@ -1,8 +1,60 @@ from fastapi import FastAPI, APIRouter +from .models import CollectionPublic, CollectionCreate, CollectionUpdate +from .models import get_collections, create_colletion, update_collection, delete_collection router = APIRouter( prefix="/collections", tags=["collections"], responses={404: {"description": "Not found"}}, dependencies=[], -) \ No newline at end of file +) + + + +@router.get("/{user_id}") +async def get_collections_api(user_id: int) -> list[CollectionPublic]: + """ + Kullanıcının collectionlarını döndürür + """ + + _collections : list[CollectionPublic] = get_collections(user_id=user_id) + + return _collections + + + +@router.post("/{user_id}") +async def create_collection( + user_id: int, + collection: CollectionCreate +) -> bool: + """ + Collection oluşturma fonksiyonu + """ + _result = create_colletion(user_id=user_id, collection=collection) + return _result + + +@router.put("/{user_id}/{collection_id}") +async def update_collection_api( + user_id: int, + collection_id : int, + collection: CollectionUpdate +) -> bool: + """ + Collection güncelleme fonksiyonu + """ + _result = update_collection(user_id=user_id, collection_id=collection_id, collection=collection) + return _result + + +@router.delete("/{user_id}/{collection_id}") +async def delete_collection_api( + user_id: int, + collection_id : int +) -> bool: + """ + Collection silme fonksiyonu + """ + _result = delete_collection(user_id=user_id, collection_id=collection_id) + return _result \ No newline at end of file diff --git a/config.py b/config.py index 2ab13c7..9657ba7 100644 --- a/config.py +++ b/config.py @@ -30,11 +30,11 @@ class Base(DeclarativeBase): #models te içe aktarmayı unutma def init_db(): - Base.metadata.drop_all(engine) # Veritabanını her başlangıcta siler burayada dikkat !!!!!!!! + #Base.metadata.drop_all(engine) # Veritabanını her başlangıcta siler burayada dikkat !!!!!!!! Base.metadata.create_all(bind=engine) # Veritabanını oluşturur # Session dependency (FastAPI için) -def get_session_db(): +def get_session_db() -> 'Generator[Session, None]': db = SessionLocal() try: yield db diff --git a/items/models.py b/items/models.py index b88a6a9..9adbf6d 100644 --- a/items/models.py +++ b/items/models.py @@ -70,10 +70,9 @@ class Items(Base): item_score: Mapped[float] = mapped_column(Float, default=0.0) # ilişkiler - collections : Mapped['CollectionsDB']= relationship( + collections : Mapped[list['CollectionsDB']]= relationship( "CollectionsDB", secondary=collection_item, back_populates="items", lazy='select' ) #back_populates karşı tarafın ismi - \ No newline at end of file