crud for collections

This commit is contained in:
Bedir Tuğra Karaabalı 2025-05-14 18:29:46 +03:00
parent bf71979982
commit 250d3f1f15
4 changed files with 195 additions and 13 deletions

View File

@ -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",
@ -40,3 +61,113 @@ class CollectionsDB(Base):
#### 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

View File

@ -1,4 +1,6 @@
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",
@ -6,3 +8,53 @@ router = APIRouter(
responses={404: {"description": "Not found"}},
dependencies=[],
)
@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

View File

@ -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

View File

@ -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