diff --git a/db/crud.py b/db/crud.py new file mode 100644 index 00000000..11d74273 --- /dev/null +++ b/db/crud.py @@ -0,0 +1,28 @@ +from sqlalchemy.orm import Session +from . import models, schemas + +def get_author(db: Session, author_id: int): + return db.query(models.Author).filter(models.Author.id == author_id).first() + +def get_authors(db: Session, skip: int = 0, limit: int = 100): + return db.query(models.Author).offset(skip).limit(limit).all() + +def create_author(db: Session, author: schemas.AuthorCreate): + db_author = models.Author(name=author.name, bio=author.bio) + db.add(db_author) + db.commit() + db.refresh(db_author) + return db_author + +def get_books(db: Session, skip: int = 0, limit: int = 100, author_id: int = None): + query = db.query(models.Book) + if author_id: + query = query.filter(models.Book.author_id == author_id) + return query.offset(skip).limit(limit).all() + +def create_book(db: Session, book: schemas.BookCreate): + db_book = models.Book(**book.model_dump()) + db.add(db_book) + db.commit() + db.refresh(db_book) + return db_book \ No newline at end of file diff --git a/db/database.py b/db/database.py new file mode 100644 index 00000000..c08fffb7 --- /dev/null +++ b/db/database.py @@ -0,0 +1,13 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +SQLALCHEMY_DATABASE_URL = "sqlite:///./library.db" + +# connect_args потрібен лише для SQLite, щоб дозволити роботу з декількома потоками +engine = create_engine( + SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() \ No newline at end of file diff --git a/db/models.py b/db/models.py new file mode 100644 index 00000000..aae4cfb0 --- /dev/null +++ b/db/models.py @@ -0,0 +1,23 @@ +from sqlalchemy import Column, Integer, String, ForeignKey, Date +from sqlalchemy.orm import relationship +from .database import Base + +class Author(Base): + __tablename__ = "authors" + + id = Column(Integer, primary_key=True, index=True) + name = Column(String, unique=True, index=True) + bio = Column(String) + + books = relationship("Book", back_populates="author") + +class Book(Base): + __tablename__ = "books" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True) + summary = Column(String) + publication_date = Column(Date) + author_id = Column(Integer, ForeignKey("authors.id")) + + author = relationship("Author", back_populates="books") \ No newline at end of file diff --git a/db/schemas.py b/db/schemas.py new file mode 100644 index 00000000..bedb832f --- /dev/null +++ b/db/schemas.py @@ -0,0 +1,32 @@ +from pydantic import BaseModel +from datetime import date +from typing import List, Optional + +class BookBase(BaseModel): + title: str + summary: str + publication_date: date + +class BookCreate(BookBase): + author_id: int + +class Book(BookBase): + id: int + author_id: int + + class Config: + from_attributes = True + +class AuthorBase(BaseModel): + name: str + bio: Optional[str] = None + +class AuthorCreate(AuthorBase): + pass + +class Author(AuthorBase): + id: int + books: List[Book] = [] + + class Config: + from_attributes = True \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 00000000..8132b19b --- /dev/null +++ b/main.py @@ -0,0 +1,40 @@ +from fastapi import FastAPI, Depends, HTTPException +from sqlalchemy.orm import Session +from db import crud, models, schemas +from db.database import SessionLocal, engine + +# Створення таблиць при запуску +models.Base.metadata.create_all(bind=engine) + +app = FastAPI() + +# Dependency для отримання сесії БД +def get_db(): + db = SessionLocal() + try: + yield db + finally: + db.close() + +@app.post("/authors/", response_model=schemas.Author) +def create_author(author: schemas.AuthorCreate, db: Session = Depends(get_db)): + return crud.create_author(db=db, author=author) + +@app.get("/authors/", response_model=list[schemas.Author]) +def read_authors(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): + return crud.get_authors(db, skip=skip, limit=limit) + +@app.get("/authors/{author_id}", response_model=schemas.Author) +def read_author(author_id: int, db: Session = Depends(get_db)): + db_author = crud.get_author(db, author_id=author_id) + if db_author is None: + raise HTTPException(status_code=404, detail="Author not found") + return db_author + +@app.post("/books/", response_model=schemas.Book) +def create_book(book: schemas.BookCreate, db: Session = Depends(get_db)): + return crud.create_book(db=db, book=book) + +@app.get("/books/", response_model=list[schemas.Book]) +def read_books(skip: int = 0, limit: int = 10, author_id: int = None, db: Session = Depends(get_db)): + return crud.get_books(db, skip=skip, limit=limit, author_id=author_id) \ No newline at end of file