Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@

# macOS
.DS_Store

# Environment / secrets
.env
4 changes: 3 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ RUN apt-get update && apt-get install -y libpq-dev
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
RUN adduser --disabled-password --gecos "" appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--log-level", "trace"]
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--log-level", "warning"]
28 changes: 20 additions & 8 deletions conftest.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import pytest
from sqlalchemy import create_engine, inspect, text
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
from fastapi.testclient import TestClient
from main import create_app
from dependencies import get_db, database_url
from models import Base


@pytest.fixture(scope="session")
def test_engine():
"""Create test database engine"""
Expand All @@ -32,14 +33,22 @@ def test_db(test_engine):
connection.close()


@pytest.fixture
@pytest.fixture(scope="function")
def test_app(test_engine):
"""Create test FastAPI application with test database"""
"""Create test FastAPI application with test database.

Uses a single connection with savepoint-based rollback so that data
written during a request is visible within the same test function but
is rolled back at the end of the test.
"""
connection = test_engine.connect()
transaction = connection.begin()
TestingSessionLocal = sessionmaker(
autocommit=False, autoflush=False, bind=connection,
join_transaction_mode="create_savepoint"
)

def override_get_db():
TestingSessionLocal = sessionmaker(
autocommit=False, autoflush=False, bind=test_engine
)
db = TestingSessionLocal()
try:
yield db
Expand All @@ -48,10 +57,13 @@ def override_get_db():

app = create_app()
app.dependency_overrides[get_db] = override_get_db
return app
yield app

transaction.rollback()
connection.close()

@pytest.fixture

@pytest.fixture(scope="function")
def client(test_app):
"""Create test client"""
return TestClient(test_app)
2 changes: 0 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ services:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
- ./db.sql:/docker-entrypoint-initdb.d/db.sql
Expand Down
18 changes: 17 additions & 1 deletion models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import re
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
from pydantic import BaseModel, ConfigDict
from pydantic import BaseModel, ConfigDict, field_validator


# SQLAlchemy models
Expand All @@ -18,13 +19,27 @@ class Book(Base):
id: Mapped[int] = mapped_column(primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(255), index=True)
author: Mapped[str] = mapped_column(String(255))
isbn: Mapped[str] = mapped_column(String(13))


# Pydantic models
class BookIn(BaseModel):
"""Pydantic model for book input"""

title: str
author: str
isbn: str

@field_validator("isbn")
@classmethod
def validate_isbn(cls, v: str) -> str:
"""Validate ISBN-10 or ISBN-13 format."""
if not re.match(r"^(?:\d{9}[\dX]|\d{13})$", v):
raise ValueError(
"isbn must be a valid ISBN-10 (9 digits + digit or X) "
"or ISBN-13 (13 digits)"
)
return v


class BookOut(BaseModel):
Expand All @@ -33,5 +48,6 @@ class BookOut(BaseModel):
id: int
title: str
author: str
isbn: str

model_config = ConfigDict(from_attributes=True)
3 changes: 2 additions & 1 deletion repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

# Create a new book
def create_book(db: Session, book: models.BookIn):
db_book = models.Book(title=book.title, author=book.author)
db_book = models.Book(title=book.title, author=book.author, isbn=book.isbn)
db.add(db_book)
db.commit()
db.refresh(db_book)
Expand All @@ -27,6 +27,7 @@ def update_book(db: Session, book_id: int, book: models.BookIn):
if db_book:
db_book.title = book.title
db_book.author = book.author
db_book.isbn = book.isbn
db.commit()
db.refresh(db_book)
return db_book
Expand Down
26 changes: 19 additions & 7 deletions routers.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from fastapi import APIRouter, Depends, HTTPException, status
import logging
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from typing import List
import models
import repositories
from dependencies import get_db

logger = logging.getLogger(__name__)

# Create router with prefix
router = APIRouter()

Expand All @@ -16,19 +18,29 @@ def create_book(book: models.BookIn, db: Session = Depends(get_db)):
try:
return repositories.create_book(db=db, book=book)
except Exception as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
logger.error("Error creating book: %s", e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="An error occurred processing your request",
) from e


@router.get(
"/books/", response_model=List[models.BookOut], status_code=status.HTTP_200_OK
"/books/", response_model=list[models.BookOut], status_code=status.HTTP_200_OK
)
def get_books(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
def get_books(
skip: int = Query(default=0, ge=0),
limit: int = Query(default=10, ge=1, le=100),
db: Session = Depends(get_db),
):
try:
return repositories.get_books(db=db, skip=skip, limit=limit)
except Exception as e:
logger.error("Error retrieving books: %s", e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="An error occurred processing your request",
) from e


@router.get(
Expand Down
Loading
Loading