items-models-import-error
This commit is contained in:
parent
938f950646
commit
7c35097c88
5 changed files with 94 additions and 32 deletions
|
|
@ -1,12 +1,12 @@
|
|||
from fastapi import HTTPException
|
||||
from sqlalchemy import Column, Integer, String, Float, Boolean, ForeignKey
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Session, relationship
|
||||
from ..config import Base
|
||||
|
||||
|
||||
|
||||
|
||||
'''
|
||||
##### veri tabanı modelleri #####
|
||||
class Collections(Base):
|
||||
__tablename__ = "collections_table"
|
||||
|
|
@ -15,4 +15,9 @@ class Collections(Base):
|
|||
user_id = Column(Integer, ForeignKey('users_table.user_id'), nullable=False)
|
||||
visibility = Column(Boolean, default=True)
|
||||
colllection_name = Column(String, default="No name")
|
||||
collection_description = Column(String, default="No description")
|
||||
collection_description = Column(String, default="No description")
|
||||
|
||||
# ilişkiler
|
||||
user = relationship("DBUser", back_populates="user_collections")
|
||||
items = relationship("Items", back_populates="collection", cascade="all, delete-orphan")
|
||||
'''
|
||||
|
|
@ -8,10 +8,11 @@ from fastapi import Depends, HTTPException
|
|||
from typing import Annotated
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from pydantic.networks import EmailStr
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import Integer, DateTime
|
||||
from sqlalchemy.orm import Session, relationship, mapped_column, Mapped
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from email.message import EmailMessage
|
||||
|
||||
import jwt
|
||||
|
||||
class Token(BaseModel):
|
||||
|
|
@ -59,16 +60,20 @@ class UserCreate(BaseModel):
|
|||
class DBUser(Base):
|
||||
__tablename__ = "users_table"
|
||||
|
||||
user_id = Column(Integer, primary_key=True, index=True)
|
||||
username = Column(String, unique=True, index=True, nullable=False)
|
||||
email = Column(String, unique=True, index=True, nullable=False)
|
||||
hashed_password = Column(String, nullable=False)
|
||||
role = Column(String, default="user")
|
||||
status = Column(String, default="active")
|
||||
created_date = Column(String, default=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"))
|
||||
bio = Column(String, default="No bio")
|
||||
collections = Column(ARRAY(String), default=['likes'])
|
||||
follower_user = Column(ARRAY(Integer), default=[])
|
||||
user_id: Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True)
|
||||
username : Mapped[str] = mapped_column(unique=True, index=True, nullable=False)
|
||||
email : Mapped[str] = mapped_column(unique=True, index=True, nullable=False)
|
||||
hashed_password : Mapped[str] = mapped_column(nullable=False)
|
||||
role : Mapped[Role] = mapped_column(default=Role.user)
|
||||
status : Mapped[Status] = mapped_column(default=Status.active)
|
||||
created_date : Mapped[datetime] = mapped_column(DateTime, default=datetime.now()) #datetime.datetime -> python, DateTime -> sqlalchemy
|
||||
bio : Mapped[str] = mapped_column(default="No bio")
|
||||
follow_users : Mapped[list[int]] = mapped_column(ARRAY(Integer), default=[]) # takip edilen kullanıcılar
|
||||
|
||||
# -> buralar diğer tablolar ile olan ilişkiler
|
||||
from ..items.models import Items
|
||||
items : Mapped[list['Items']] = relationship("Items", back_populates="user", cascade="all, delete-orphan", lazy='select')
|
||||
|
||||
|
||||
|
||||
### AUTH ###
|
||||
|
|
|
|||
12
config.py
12
config.py
|
|
@ -1,6 +1,5 @@
|
|||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.orm import sessionmaker, DeclarativeBase
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from passlib.context import CryptContext
|
||||
|
|
@ -21,11 +20,16 @@ DATABASE_URL = os.getenv("DATABASE_URL")
|
|||
engine = create_engine(DATABASE_URL, echo=False)
|
||||
# Session factory oluştur
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base() #sqlalchemy için bu sınıfı kullanıyoruz 'class DBUser(Base)' şeklinde tanımlıyoruz
|
||||
#Base = declarative_base() #sqlalchemy için bu sınıfı kullanıyoruz 'class DBUser(Base)' şeklinde tanımlıyoruz
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass #yeni sqlalchemy sürümünde bu sınıfı kullanıyoruz
|
||||
|
||||
|
||||
#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)
|
||||
|
||||
# Session dependency (FastAPI için)
|
||||
|
|
|
|||
|
|
@ -1,12 +1,19 @@
|
|||
from datetime import datetime, timedelta, timezone
|
||||
from typing import Annotated
|
||||
|
||||
from sqlalchemy import DateTime
|
||||
from pydantic import BaseModel
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.orm import Session, relationship, mapped_column, Mapped
|
||||
from sqlalchemy import ForeignKey, Column, Integer, String, Float
|
||||
from sqlalchemy.dialects.postgresql import ARRAY
|
||||
from ..auth.models import DBUser, Role, Status, UserBase
|
||||
from ..config import Base, get_session_db
|
||||
from typing import TYPE_CHECKING
|
||||
from ..auth.models import Role, Status, UserBase
|
||||
|
||||
####!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
|
||||
from ..auth.models import DBUser # -> tam burda bir hata var circle import yaparken karışıyor nasıl çözülecek bilmiyorum
|
||||
|
||||
|
||||
class UserProfileBase(UserBase):
|
||||
bio : str | None = None
|
||||
|
|
@ -26,26 +33,44 @@ class UserProfilePrivate(UserProfilePublic):
|
|||
status : Status | None = None
|
||||
follow_user : list[int] | None = None
|
||||
|
||||
|
||||
|
||||
######## ITEMS ######
|
||||
|
||||
class BaseItem(BaseModel):
|
||||
item_created_date : datetime | None = None
|
||||
item_location : str | None = None
|
||||
item_type : str | None = None
|
||||
item_content : str | None = None
|
||||
|
||||
class ItemCreate(BaseItem): # item oluşturma için ekstra bir ihtiyaci olmaz
|
||||
pass
|
||||
|
||||
##### VERİTABANI MODELİ #####
|
||||
# Tüm modeller AUTH'da veri tabanına işlendi yukardaki
|
||||
#modeller veri tabanında mevcuttur. Değiştirmek için AUTH'daki
|
||||
# DBUser modelini değiştirip tekrar veri tabanına işleyebilirsin
|
||||
|
||||
'''
|
||||
'''
|
||||
class Items(Base):
|
||||
__tablename__ = "items_table"
|
||||
|
||||
item_id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users_table.user_id"), nullable=False)
|
||||
#collection_id = Column(Integer, ForeignKey("collections_table.collection_id"), nullable=False)
|
||||
item_created_date = Column(String, default=datetime.now())
|
||||
item_location = Column(String, default="No location") #daha net tanımlancak
|
||||
item_id : Mapped[int] = mapped_column(primary_key=True, index=True, autoincrement=True)
|
||||
user_id : Mapped[int] = mapped_column(ForeignKey('users_table.user_id'), nullable=False, index=True)
|
||||
item_created_date : Mapped[datetime] = mapped_column(DateTime, default=datetime.now())
|
||||
item_location = Column(String, default="No location")
|
||||
item_type = Column(String, default="No type")
|
||||
item_content = Column(String, default="No content")
|
||||
item_score = Column(Float, default=0.0)
|
||||
|
||||
# ilişkiler
|
||||
|
||||
user : Mapped['DBUser'] = relationship("DBUser", back_populates="items", lazy='select')
|
||||
#collection = relationship("Collections", back_populates="items")
|
||||
|
||||
|
||||
|
||||
|
||||
'''
|
||||
'''
|
||||
def is_user_exsist(username : str, session : Annotated[Session, Depends(get_session_db)]) -> bool | UserProfilePublic:
|
||||
#DBUser veritabanındaki nesnedir her niteliğe sahiptir
|
||||
user = session.query(DBUser).filter(DBUser.username == username).first()
|
||||
|
|
@ -66,5 +91,21 @@ def all_users(session: Annotated[Session, Depends(get_session_db)]) -> list[User
|
|||
) for user in users]
|
||||
|
||||
|
||||
def add_Item_user(
|
||||
user: Annotated[UserProfileID, Depends(get_session_db)],
|
||||
session: Annotated[Session, Depends(get_session_db)],
|
||||
item: ItemCreate) -> bool:
|
||||
# DBUser veritabanındaki nesnedir her niteliğe sahiptir
|
||||
|
||||
item = Items(
|
||||
user_id=user.user_id,
|
||||
item_location=item.item_location,
|
||||
item_type=item.item_type,
|
||||
item_content=item.item_content,
|
||||
item_score=item.item_score,
|
||||
item_created_date=item.item_created_date
|
||||
)
|
||||
|
||||
session.add(item)
|
||||
session.commit()
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from .models import UserProfileBase, UserProfileID, UserProfilePrivate, UserProfilePublic, all_users, is_user_exsist
|
||||
from .models import ItemCreate, UserProfileBase, UserProfileID, UserProfilePrivate, UserProfilePublic, add_Item_user, all_users, is_user_exsist
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from ..config import get_session_db
|
||||
|
|
@ -42,7 +42,14 @@ async def get_user_profile_me(
|
|||
async def create_user_profile(
|
||||
user : Annotated[UserProfileID, Depends(get_current_active_user)],
|
||||
session: Annotated[Session, Depends(get_session_db)],
|
||||
) -> UserProfileBase:
|
||||
item : Annotated[ItemCreate , None] = None
|
||||
) -> dict:
|
||||
|
||||
return user
|
||||
if add_Item_user(user, session, item) :
|
||||
return {"message": "User item created successfully"}
|
||||
|
||||
return {"error": "User item creation failed"}
|
||||
|
||||
|
||||
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue