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
149 changes: 149 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/migrations

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .


# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions

# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = sqlite:///./library.db


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME

# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME

# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARNING
handlers = console
qualname =

[logger_sqlalchemy]
level = WARNING
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
68 changes: 68 additions & 0 deletions crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from fastapi import HTTPException
from sqlalchemy.orm import Session

import models
import schemas

Comment on lines +5 to +6
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task specifies the Author model's name field should be unique, but there's no unique=True constraint in the model definition. The uniqueness check exists in the API layer, but the database constraint is missing.


def get_all_books(db: Session, skip: int, limit: int, author_id: int | None = None):
queryset = db.query(models.Book)

if author_id:
queryset = queryset.filter(
Comment on lines +10 to +12
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requires author_id as the foreign key field name, but the schema uses author which is inconsistent with the requirements and misleading since it suggests an Author object rather than an ID.

models.Book.author_id == author_id
)

return queryset.offset(skip).limit(limit).all()


def get_book_by_id(db: Session, id: int):
return db.query(models.Book).get(id)


def get_book_by_title(db: Session, title: str):
Comment on lines +20 to +23
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requirements specify pagination with skip and limit query parameters, but this endpoint uses page. Change to: skip: int = Query(0, ge=0), limit: int = Query(10, ge=1) and pass skip and limit directly to the CRUD function.

return db.query(models.Book).filter(
models.Book.title == title,
Comment on lines +20 to +25
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requirements specify pagination using skip and limit parameters, but the implementation uses a custom page parameter with hardcoded page size. Consider implementing according to the specified requirements.

).first()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The skip parameter has ge=1 constraint, but pagination typically starts at 0. Consider changing to ge=0 with a default of 0.


Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The limit parameter has ge=2 constraint and default of 2. For flexible pagination, consider ge=1 with a sensible default like 10 or 100.


def create_book(db: Session, book: schemas.BookCreate):
db_book = models.Book(
title=book.title,
summary=book.summary,
publication_date=book.publication_date,
Comment on lines +28 to +33
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requires author_id as the foreign key field name, but this uses book.author. This should be author_id to match the task requirements.

author_id=book.author,
)

db.add(db_book)
db.commit()
db.refresh(db_book)

return db_book


def get_all_authors(db: Session, skip: int, limit: int, ):
return db.query(models.Author).offset(skip).limit(limit).all()


def get_author_by_id(db: Session, id: int):
return db.query(models.Author).get(id)


def get_author_by_name(db: Session, name: str):
return db.query(models.Author).filter(
Comment on lines +51 to +53
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requirements specify pagination with skip and limit query parameters, but this endpoint uses page. Change to: skip: int = Query(0, ge=0), limit: int = Query(10, ge=1) and pass skip and limit directly to the CRUD function.

models.Author.name == name,
).first()
Comment on lines +51 to +55
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task requirements specify pagination using skip and limit parameters, but the implementation uses a custom page parameter with hardcoded page size. Consider implementing according to the specified requirements.



def create_author(db: Session, author: schemas.AuthorCreate):
db_author = models.Author(
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The skip parameter has ge=1 constraint. Consider changing to ge=0 with a default of 0 for consistency with pagination standards.

name=author.name,
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The limit parameter has ge=2 constraint. Consider changing to ge=1 for more flexible pagination options.

bio=author.bio,
)

db.add(db_author)
db.commit()
db.refresh(db_author)

return db_author
21 changes: 21 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from sqlalchemy import create_engine
from sqlalchemy.orm import declarative_base, sessionmaker


SQLALCHEMY_DATABASE_URL = "sqlite:///./library.db"


engine = create_engine(
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The get_all_books function uses a page parameter, but the requirements explicitly specify using skip and limit for pagination. Change signature to get_all_books(db: Session, skip: int = 0, limit: int = 10, author_id: int | None = None) and use these directly in the query instead of calculating offset.

SQLALCHEMY_DATABASE_URL,
connect_args={
"check_same_thread": False
}
)
SessionLocal = sessionmaker(
bind=engine,
autoflush=False,
autocommit=False,
)

Comment on lines +13 to +19
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The BookCreate schema defines 'author' as an integer (for author_id), but Book response schema defines 'author' as Optional[Author] object. This inconsistency will cause serialization issues when returning Book objects - the database only has author_id (integer), not an Author object.


Base = declarative_base()
87 changes: 87 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
from fastapi import FastAPI, Depends, HTTPException, Query
from sqlalchemy.orm import Session

import crud
from database import SessionLocal
import schemas
Comment on lines +5 to +6
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name field is missing unique=True. The requirements specify that Author.name should be unique.



Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task explicitly requires 'pagination (skip, limit)' but this function uses a page parameter. Should use skip and limit parameters instead: def get_all_books(db: Session, skip: int = 0, limit: int = 10, author_id: int | None = None): and remove the offset calculation.

app = FastAPI()


def get_db():
db = SessionLocal()
yield db
db.close()


@app.get("/")
def hello_world():
return "Hello World!!!"


@app.get("/books/", response_model=list[schemas.Book])
def read_books(
author_id: int | None = None,
db: Session = Depends(get_db),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task explicitly requires pagination with 'skip, limit' query parameters, not 'page'. Should change to: skip: int = Query(0, ge=0), limit: int = Query(10, ge=1)

skip: int = Query(1, ge=1),
Comment on lines +26 to +27
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The skip parameter should default to 0 (not 1) since skip=0 means 'start from the beginning' in pagination. Currently, this would skip the first record by default. Change to Query(0, ge=0).

limit: int = Query(2, ge=2),
):
return crud.get_all_books(db, skip=skip, limit=limit, author_id=author_id)


Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The response_model should be schemas.Book (not BookCreate) to return the created book with its ID. BookCreate is for input validation only.

@app.post("/books/", response_model=schemas.Book)
def create_book(
book: schemas.BookCreate,
db: Session = Depends(get_db),
):
if crud.get_book_by_title(db=db, title=book.title):
raise HTTPException(400, "Such book alredy exists")

return crud.create_book(db=db, book=book)


@app.get("/books/{book_id}/", response_model=schemas.Book)
def read_book_details(
book_id: int,
db: Session = Depends(get_db),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task explicitly requires 'pagination (skip, limit)' but this function uses a page parameter. Should use skip and limit parameters instead: def get_all_authors(db: Session, skip: int = 0, limit: int = 10): and remove the offset calculation.

):
book = crud.get_book_by_id(db=db, id=book_id)

if not book:
raise HTTPException(400, "No book with such id")

return book


@app.get("/authors/", response_model=list[schemas.Author])
def read_authors(
db: Session = Depends(get_db),
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The task explicitly requires pagination with 'skip, limit' query parameters, not 'page'. Should change to: skip: int = Query(0, ge=0), limit: int = Query(10, ge=1)

skip: int = Query(1, ge=1),
Comment on lines +59 to +60
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The skip parameter should default to 0 (not 1) for consistency with the books endpoint. Change to Query(0, ge=0).

limit: int = Query(2, ge=2),
):
return crud.get_all_authors(db, skip=skip, limit=limit)


@app.post("/authors/", response_model=schemas.Author)
def create_author(
author: schemas.AuthorCreate,
db: Session = Depends(get_db),
):
if crud.get_author_by_name(db=db, name=author.name):
raise HTTPException(400, "Such author alredy exists")

return crud.create_author(db=db, author=author)


@app.get("/authors/{author_id}/", response_model=schemas.Author)
def read_author_details(
author_id: int,
db: Session = Depends(get_db),
):
author = crud.get_author_by_id(db=db, id=author_id)

if not author:
raise HTTPException(400, "No author with such id")

return author
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
Loading