Create manga inventory API with FastAPI and SQLite

- Implemented CRUD operations for manga, authors, publishers, and genres
- Added search and filtering functionality
- Set up SQLAlchemy ORM with SQLite database
- Configured Alembic for database migrations
- Implemented logging with Loguru
- Added comprehensive API documentation
- Set up error handling and validation
- Added ruff for linting and formatting
This commit is contained in:
Automated Action 2025-05-30 12:29:35 +00:00
parent f05d532b0c
commit a9210ca8ed
39 changed files with 2011 additions and 2 deletions

171
README.md
View File

@ -1,3 +1,170 @@
# FastAPI Application
# Manga Inventory API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A FastAPI-based RESTful API for managing a manga book inventory.
## Features
- Complete CRUD operations for manga books, authors, publishers, and genres
- Search and filtering capabilities for manga inventory
- SQLite database with SQLAlchemy ORM
- Alembic for database migrations
- Pydantic for data validation
- Comprehensive logging with Loguru
## Tech Stack
- Python 3.10+
- FastAPI
- SQLAlchemy
- Alembic
- Pydantic
- SQLite
- Loguru
## Project Structure
```
manga-inventory-api/
├── alembic.ini
├── app/
│ ├── api/
│ │ ├── deps.py
│ │ └── v1/
│ │ ├── api.py
│ │ └── endpoints/
│ │ ├── author.py
│ │ ├── genre.py
│ │ ├── manga.py
│ │ └── publisher.py
│ ├── core/
│ │ ├── config.py
│ │ └── logging.py
│ ├── crud/
│ │ ├── author.py
│ │ ├── base.py
│ │ ├── genre.py
│ │ ├── manga.py
│ │ └── publisher.py
│ ├── db/
│ │ ├── base.py
│ │ ├── base_class.py
│ │ └── session.py
│ ├── models/
│ │ └── manga.py
│ └── schemas/
│ ├── author.py
│ ├── genre.py
│ ├── manga.py
│ └── publisher.py
├── main.py
├── migrations/
│ ├── env.py
│ ├── README
│ ├── script.py.mako
│ └── versions/
│ └── 01_initial_tables.py
├── pyproject.toml
└── requirements.txt
```
## Setup and Installation
1. Clone the repository:
```bash
git clone <repository-url>
cd manga-inventory-api
```
2. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```
3. Install the dependencies:
```bash
pip install -r requirements.txt
```
4. Run the database migrations:
```bash
alembic upgrade head
```
5. Start the development server:
```bash
uvicorn main:app --reload
```
6. The API will be available at http://localhost:8000
## API Endpoints
### Health Check
- `GET /health` - Check if the API is running
### Manga
- `GET /api/v1/manga` - List all manga
- `POST /api/v1/manga` - Create a new manga
- `GET /api/v1/manga/{manga_id}` - Get a specific manga
- `PUT /api/v1/manga/{manga_id}` - Update a manga
- `DELETE /api/v1/manga/{manga_id}` - Delete a manga
### Authors
- `GET /api/v1/authors` - List all authors
- `POST /api/v1/authors` - Create a new author
- `GET /api/v1/authors/{author_id}` - Get a specific author
- `PUT /api/v1/authors/{author_id}` - Update an author
- `DELETE /api/v1/authors/{author_id}` - Delete an author
### Publishers
- `GET /api/v1/publishers` - List all publishers
- `POST /api/v1/publishers` - Create a new publisher
- `GET /api/v1/publishers/{publisher_id}` - Get a specific publisher
- `PUT /api/v1/publishers/{publisher_id}` - Update a publisher
- `DELETE /api/v1/publishers/{publisher_id}` - Delete a publisher
### Genres
- `GET /api/v1/genres` - List all genres
- `POST /api/v1/genres` - Create a new genre
- `GET /api/v1/genres/{genre_id}` - Get a specific genre
- `PUT /api/v1/genres/{genre_id}` - Update a genre
- `DELETE /api/v1/genres/{genre_id}` - Delete a genre
## Filtering and Searching
You can filter manga using query parameters:
```
GET /api/v1/manga?title=Naruto&in_stock=true
```
Available filters:
- `title` - Filter by title (partial match)
- `author_id` - Filter by author ID
- `publisher_id` - Filter by publisher ID
- `genre_id` - Filter by genre ID
- `in_stock` - Filter by stock availability (true/false)
## Documentation
Interactive API documentation is available at:
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
## Development
### Code Formatting and Linting
The project uses Ruff for linting and formatting:
```bash
# Format code
ruff format .
# Lint code
ruff check .
# Fix auto-fixable linting issues
ruff check --fix .
```

111
alembic.ini Normal file
View File

@ -0,0 +1,111 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = 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
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# 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 migrations/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 "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
# 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
# SQLite URL using absolute path
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
[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
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
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

0
app/__init__.py Normal file
View File

0
app/api/__init__.py Normal file
View File

14
app/api/deps.py Normal file
View File

@ -0,0 +1,14 @@
from collections.abc import Generator
from app.db.session import SessionLocal
def get_db() -> Generator:
"""
Dependency for getting a database session.
"""
db = SessionLocal()
try:
yield db
finally:
db.close()

0
app/api/v1/__init__.py Normal file
View File

11
app/api/v1/api.py Normal file
View File

@ -0,0 +1,11 @@
from fastapi import APIRouter
from app.api.v1 import endpoints
api_router = APIRouter()
# Include all endpoint routers here
api_router.include_router(endpoints.manga.router, prefix="/manga", tags=["manga"])
api_router.include_router(endpoints.author.router, prefix="/authors", tags=["authors"])
api_router.include_router(endpoints.publisher.router, prefix="/publishers", tags=["publishers"])
api_router.include_router(endpoints.genre.router, prefix="/genres", tags=["genres"])

View File

@ -0,0 +1,4 @@
# Import all endpoints modules here
from app.api.v1.endpoints import author, genre, manga, publisher
__all__ = ["author", "genre", "manga", "publisher"]

View File

@ -0,0 +1,116 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=list[schemas.Author])
def read_authors(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve authors.
"""
authors = crud.author.get_multi(db, skip=skip, limit=limit)
return authors
@router.post("/", response_model=schemas.Author)
def create_author(
*,
db: Session = Depends(deps.get_db),
author_in: schemas.AuthorCreate,
) -> Any:
"""
Create new author.
"""
author = crud.author.get_by_name(db, name=author_in.name)
if author:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="An author with this name already exists.",
)
author = crud.author.create(db, obj_in=author_in)
return author
@router.get("/{author_id}", response_model=schemas.Author)
def read_author(
*,
db: Session = Depends(deps.get_db),
author_id: int,
) -> Any:
"""
Get author by ID.
"""
author = crud.author.get(db, id=author_id)
if not author:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Author not found",
)
return author
@router.put("/{author_id}", response_model=schemas.Author)
def update_author(
*,
db: Session = Depends(deps.get_db),
author_id: int,
author_in: schemas.AuthorUpdate,
) -> Any:
"""
Update an author.
"""
author = crud.author.get(db, id=author_id)
if not author:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Author not found",
)
# Check if updating to an existing name
if author_in.name and author_in.name != author.name:
existing_author = crud.author.get_by_name(db, name=author_in.name)
if existing_author:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="An author with this name already exists.",
)
author = crud.author.update(db, db_obj=author, obj_in=author_in)
return author
@router.delete("/{author_id}", response_model=schemas.Author)
def delete_author(
*,
db: Session = Depends(deps.get_db),
author_id: int,
) -> Any:
"""
Delete an author.
"""
author = crud.author.get(db, id=author_id)
if not author:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Author not found",
)
# Check if author has manga associated with it
if author.manga_list:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot delete author with associated manga. Remove manga first.",
)
author = crud.author.remove(db, id=author_id)
return author

View File

@ -0,0 +1,116 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=list[schemas.Genre])
def read_genres(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve genres.
"""
genres = crud.genre.get_multi(db, skip=skip, limit=limit)
return genres
@router.post("/", response_model=schemas.Genre)
def create_genre(
*,
db: Session = Depends(deps.get_db),
genre_in: schemas.GenreCreate,
) -> Any:
"""
Create new genre.
"""
genre = crud.genre.get_by_name(db, name=genre_in.name)
if genre:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A genre with this name already exists.",
)
genre = crud.genre.create(db, obj_in=genre_in)
return genre
@router.get("/{genre_id}", response_model=schemas.Genre)
def read_genre(
*,
db: Session = Depends(deps.get_db),
genre_id: int,
) -> Any:
"""
Get genre by ID.
"""
genre = crud.genre.get(db, id=genre_id)
if not genre:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Genre not found",
)
return genre
@router.put("/{genre_id}", response_model=schemas.Genre)
def update_genre(
*,
db: Session = Depends(deps.get_db),
genre_id: int,
genre_in: schemas.GenreUpdate,
) -> Any:
"""
Update a genre.
"""
genre = crud.genre.get(db, id=genre_id)
if not genre:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Genre not found",
)
# Check if updating to an existing name
if genre_in.name and genre_in.name != genre.name:
existing_genre = crud.genre.get_by_name(db, name=genre_in.name)
if existing_genre:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A genre with this name already exists.",
)
genre = crud.genre.update(db, db_obj=genre, obj_in=genre_in)
return genre
@router.delete("/{genre_id}", response_model=schemas.Genre)
def delete_genre(
*,
db: Session = Depends(deps.get_db),
genre_id: int,
) -> Any:
"""
Delete a genre.
"""
genre = crud.genre.get(db, id=genre_id)
if not genre:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Genre not found",
)
# Check if genre has manga associated with it
if genre.manga_list:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot delete genre with associated manga. Remove manga first.",
)
genre = crud.genre.remove(db, id=genre_id)
return genre

View File

@ -0,0 +1,193 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=list[schemas.MangaWithRelations])
def read_manga(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
title: str | None = None,
author_id: int | None = None,
publisher_id: int | None = None,
genre_id: int | None = None,
in_stock: bool | None = None,
) -> Any:
"""
Retrieve manga.
- **title**: Optional filter by title (partial match)
- **author_id**: Optional filter by author ID
- **publisher_id**: Optional filter by publisher ID
- **genre_id**: Optional filter by genre ID
- **in_stock**: Optional filter by stock availability
"""
if any([title, author_id, publisher_id, genre_id, in_stock is not None]):
# Search with filters
manga = crud.manga.search(
db,
title=title,
author_id=author_id,
publisher_id=publisher_id,
genre_id=genre_id,
in_stock=in_stock,
skip=skip,
limit=limit,
)
else:
# Get all manga
manga = crud.manga.get_multi(db, skip=skip, limit=limit)
return manga
@router.post("/", response_model=schemas.MangaWithRelations)
def create_manga(
*,
db: Session = Depends(deps.get_db),
manga_in: schemas.MangaCreate,
) -> Any:
"""
Create new manga.
"""
# Check if ISBN exists and is not empty
if manga_in.isbn:
manga = crud.manga.get_by_isbn(db, isbn=manga_in.isbn)
if manga:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A manga with this ISBN already exists.",
)
# Validate author_id if provided
if manga_in.author_id:
author = crud.author.get(db, id=manga_in.author_id)
if not author:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Author with ID {manga_in.author_id} not found.",
)
# Validate publisher_id if provided
if manga_in.publisher_id:
publisher = crud.publisher.get(db, id=manga_in.publisher_id)
if not publisher:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Publisher with ID {manga_in.publisher_id} not found.",
)
# Validate genre_ids if provided
if manga_in.genre_ids:
for genre_id in manga_in.genre_ids:
genre = crud.genre.get(db, id=genre_id)
if not genre:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Genre with ID {genre_id} not found.",
)
manga = crud.manga.create(db, obj_in=manga_in)
return manga
@router.get("/{manga_id}", response_model=schemas.MangaWithRelations)
def read_manga_by_id(
*,
db: Session = Depends(deps.get_db),
manga_id: int,
) -> Any:
"""
Get manga by ID.
"""
manga = crud.manga.get(db, id=manga_id)
if not manga:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Manga not found",
)
return manga
@router.put("/{manga_id}", response_model=schemas.MangaWithRelations)
def update_manga(
*,
db: Session = Depends(deps.get_db),
manga_id: int,
manga_in: schemas.MangaUpdate,
) -> Any:
"""
Update a manga.
"""
manga = crud.manga.get(db, id=manga_id)
if not manga:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Manga not found",
)
# Check if ISBN is being updated and already exists
if manga_in.isbn and manga_in.isbn != manga.isbn:
existing_manga = crud.manga.get_by_isbn(db, isbn=manga_in.isbn)
if existing_manga:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A manga with this ISBN already exists.",
)
# Validate author_id if provided
if manga_in.author_id:
author = crud.author.get(db, id=manga_in.author_id)
if not author:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Author with ID {manga_in.author_id} not found.",
)
# Validate publisher_id if provided
if manga_in.publisher_id:
publisher = crud.publisher.get(db, id=manga_in.publisher_id)
if not publisher:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Publisher with ID {manga_in.publisher_id} not found.",
)
# Validate genre_ids if provided
if manga_in.genre_ids:
for genre_id in manga_in.genre_ids:
genre = crud.genre.get(db, id=genre_id)
if not genre:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Genre with ID {genre_id} not found.",
)
manga = crud.manga.update(db, db_obj=manga, obj_in=manga_in)
return manga
@router.delete("/{manga_id}", response_model=schemas.Manga)
def delete_manga(
*,
db: Session = Depends(deps.get_db),
manga_id: int,
) -> Any:
"""
Delete a manga.
"""
manga = crud.manga.get(db, id=manga_id)
if not manga:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Manga not found",
)
manga = crud.manga.remove(db, id=manga_id)
return manga

View File

@ -0,0 +1,116 @@
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app import crud, schemas
from app.api import deps
router = APIRouter()
@router.get("/", response_model=list[schemas.Publisher])
def read_publishers(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> Any:
"""
Retrieve publishers.
"""
publishers = crud.publisher.get_multi(db, skip=skip, limit=limit)
return publishers
@router.post("/", response_model=schemas.Publisher)
def create_publisher(
*,
db: Session = Depends(deps.get_db),
publisher_in: schemas.PublisherCreate,
) -> Any:
"""
Create new publisher.
"""
publisher = crud.publisher.get_by_name(db, name=publisher_in.name)
if publisher:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A publisher with this name already exists.",
)
publisher = crud.publisher.create(db, obj_in=publisher_in)
return publisher
@router.get("/{publisher_id}", response_model=schemas.Publisher)
def read_publisher(
*,
db: Session = Depends(deps.get_db),
publisher_id: int,
) -> Any:
"""
Get publisher by ID.
"""
publisher = crud.publisher.get(db, id=publisher_id)
if not publisher:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Publisher not found",
)
return publisher
@router.put("/{publisher_id}", response_model=schemas.Publisher)
def update_publisher(
*,
db: Session = Depends(deps.get_db),
publisher_id: int,
publisher_in: schemas.PublisherUpdate,
) -> Any:
"""
Update a publisher.
"""
publisher = crud.publisher.get(db, id=publisher_id)
if not publisher:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Publisher not found",
)
# Check if updating to an existing name
if publisher_in.name and publisher_in.name != publisher.name:
existing_publisher = crud.publisher.get_by_name(db, name=publisher_in.name)
if existing_publisher:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A publisher with this name already exists.",
)
publisher = crud.publisher.update(db, db_obj=publisher, obj_in=publisher_in)
return publisher
@router.delete("/{publisher_id}", response_model=schemas.Publisher)
def delete_publisher(
*,
db: Session = Depends(deps.get_db),
publisher_id: int,
) -> Any:
"""
Delete a publisher.
"""
publisher = crud.publisher.get(db, id=publisher_id)
if not publisher:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Publisher not found",
)
# Check if publisher has manga associated with it
if publisher.manga_list:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot delete publisher with associated manga. Remove manga first.",
)
publisher = crud.publisher.remove(db, id=publisher_id)
return publisher

0
app/core/__init__.py Normal file
View File

26
app/core/config.py Normal file
View File

@ -0,0 +1,26 @@
from pydantic import AnyHttpUrl, validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Manga Inventory API"
VERSION: str = "0.1.0"
# CORS Configuration
BACKEND_CORS_ORIGINS: list[str | AnyHttpUrl] = []
@validator("BACKEND_CORS_ORIGINS", pre=True)
def assemble_cors_origins(self, v: str | list[str]) -> list[str] | str:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, list | str):
return v
raise ValueError(v)
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()

86
app/core/logging.py Normal file
View File

@ -0,0 +1,86 @@
import logging
import sys
from loguru import logger
from pydantic import BaseModel
class LogConfig(BaseModel):
"""Logging configuration"""
LOGGER_NAME: str = "manga_inventory_api"
LOG_FORMAT: str = (
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
"<level>{level: <8}</level> | "
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
"<level>{message}</level>"
)
LOG_LEVEL: str = "INFO"
LOG_FILE_PATH: str | None = None
LOG_ROTATION: str | None = "20 MB"
LOG_RETENTION: str | None = "1 week"
LOG_JSON: bool = False
def setup_logging(config: LogConfig = LogConfig()) -> None:
"""Configure Loguru logger"""
# Intercept standard logging
logging.getLogger().handlers = [InterceptHandler()]
# Remove default handlers
logger.remove()
# Add console handler
logger.add(
sys.stdout,
enqueue=True,
backtrace=True,
format=config.LOG_FORMAT,
level=config.LOG_LEVEL,
colorize=True,
)
# Add file handler if path is specified
if config.LOG_FILE_PATH:
logger.add(
config.LOG_FILE_PATH,
rotation=config.LOG_ROTATION,
retention=config.LOG_RETENTION,
enqueue=True,
backtrace=True,
format=config.LOG_FORMAT,
level=config.LOG_LEVEL,
colorize=False,
serialize=config.LOG_JSON,
)
# Configure standard library logging
for _log in ["uvicorn", "uvicorn.error", "fastapi"]:
_logger = logging.getLogger(_log)
_logger.handlers = [InterceptHandler()]
_logger.propagate = False
logger.info("Logging configured successfully")
class InterceptHandler(logging.Handler):
"""
Intercept handler for standard library logging to redirect to loguru.
"""
def emit(self, record: logging.LogRecord) -> None:
"""
Intercepts log records and redirects them to loguru.
"""
try:
level = logger.level(record.levelname).name
except ValueError:
level = record.levelno
frame, depth = logging.currentframe(), 2
while frame.f_code.co_filename == logging.__file__:
frame = frame.f_back
depth += 1
logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())

6
app/crud/__init__.py Normal file
View File

@ -0,0 +1,6 @@
from app.crud.author import author
from app.crud.genre import genre
from app.crud.manga import manga
from app.crud.publisher import publisher
__all__ = ["author", "genre", "manga", "publisher"]

22
app/crud/author.py Normal file
View File

@ -0,0 +1,22 @@
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.manga import Author
from app.schemas.author import AuthorCreate, AuthorUpdate
class CRUDAuthor(CRUDBase[Author, AuthorCreate, AuthorUpdate]):
def get_by_name(self, db: Session, *, name: str) -> Author | None:
"""
Get an author by name.
"""
return db.query(Author).filter(Author.name == name).first()
def get_multi_with_manga(self, db: Session, *, skip: int = 0, limit: int = 100) -> list[Author]:
"""
Get multiple authors with their manga lists.
"""
return db.query(Author).offset(skip).limit(limit).all()
author = CRUDAuthor(Author)

75
app/crud/base.py Normal file
View File

@ -0,0 +1,75 @@
from typing import Any, Generic, TypeVar
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
from sqlalchemy.orm import Session
from app.db.base_class import Base
ModelType = TypeVar("ModelType", bound=Base)
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
def __init__(self, model: type[ModelType]):
"""
CRUD object with default methods to Create, Read, Update, Delete (CRUD).
**Parameters**
* `model`: A SQLAlchemy model class
* `schema`: A Pydantic model (schema) class
"""
self.model = model
def get(self, db: Session, id: Any) -> ModelType | None:
"""
Get a record by ID.
"""
return db.query(self.model).filter(self.model.id == id).first()
def get_multi(self, db: Session, *, skip: int = 0, limit: int = 100) -> list[ModelType]:
"""
Get multiple records with pagination.
"""
return db.query(self.model).offset(skip).limit(limit).all()
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
"""
Create a new record.
"""
obj_in_data = jsonable_encoder(obj_in)
db_obj = self.model(**obj_in_data)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def update(
self, db: Session, *, db_obj: ModelType, obj_in: UpdateSchemaType | dict[str, Any]
) -> ModelType:
"""
Update a record.
"""
obj_data = jsonable_encoder(db_obj)
if isinstance(obj_in, dict):
update_data = obj_in
else:
update_data = obj_in.dict(exclude_unset=True)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def remove(self, db: Session, *, id: int) -> ModelType:
"""
Delete a record.
"""
obj = db.query(self.model).get(id)
db.delete(obj)
db.commit()
return obj

28
app/crud/genre.py Normal file
View File

@ -0,0 +1,28 @@
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.manga import Genre
from app.schemas.genre import GenreCreate, GenreUpdate
class CRUDGenre(CRUDBase[Genre, GenreCreate, GenreUpdate]):
def get_by_name(self, db: Session, *, name: str) -> Genre | None:
"""
Get a genre by name.
"""
return db.query(Genre).filter(Genre.name == name).first()
def create_if_not_exists(
self, db: Session, *, name: str, description: str | None = None
) -> Genre:
"""
Create a genre if it doesn't exist, otherwise return the existing one.
"""
genre = self.get_by_name(db, name=name)
if not genre:
genre_in = GenreCreate(name=name, description=description)
genre = self.create(db, obj_in=genre_in)
return genre
genre = CRUDGenre(Genre)

144
app/crud/manga.py Normal file
View File

@ -0,0 +1,144 @@
from typing import Any
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session, joinedload
from app.crud.base import CRUDBase
from app.models.manga import Manga, MangaGenre
from app.schemas.manga import MangaCreate, MangaUpdate
class CRUDManga(CRUDBase[Manga, MangaCreate, MangaUpdate]):
def get(self, db: Session, id: Any) -> Manga | None:
"""
Get a manga by ID with all relationships loaded.
"""
return (
db.query(Manga)
.filter(Manga.id == id)
.options(
joinedload(Manga.author),
joinedload(Manga.publisher),
joinedload(Manga.genres).joinedload(MangaGenre.genre),
)
.first()
)
def get_by_isbn(self, db: Session, *, isbn: str) -> Manga | None:
"""
Get a manga by ISBN.
"""
return db.query(Manga).filter(Manga.isbn == isbn).first()
def get_multi(self, db: Session, *, skip: int = 0, limit: int = 100) -> list[Manga]:
"""
Get multiple manga with all relationships loaded.
"""
return (
db.query(Manga)
.options(
joinedload(Manga.author),
joinedload(Manga.publisher),
joinedload(Manga.genres).joinedload(MangaGenre.genre),
)
.offset(skip)
.limit(limit)
.all()
)
def create(self, db: Session, *, obj_in: MangaCreate) -> Manga:
"""
Create a new manga with genre relationships.
"""
obj_in_data = jsonable_encoder(obj_in, exclude={"genre_ids"})
db_obj = Manga(**obj_in_data)
db.add(db_obj)
db.flush() # Flush to get the ID
# Add genres if provided
if obj_in.genre_ids:
for genre_id in obj_in.genre_ids:
manga_genre = MangaGenre(manga_id=db_obj.id, genre_id=genre_id)
db.add(manga_genre)
db.commit()
db.refresh(db_obj)
return db_obj
def update(self, db: Session, *, db_obj: Manga, obj_in: MangaUpdate | dict[str, Any]) -> Manga:
"""
Update a manga with genre relationships.
"""
if isinstance(obj_in, dict):
update_data = obj_in
genre_ids = update_data.pop("genre_ids", None)
else:
update_data = obj_in.dict(exclude_unset=True)
genre_ids = update_data.pop("genre_ids", None) if "genre_ids" in update_data else None
# Update the manga object
obj_data = jsonable_encoder(db_obj)
for field in obj_data:
if field in update_data:
setattr(db_obj, field, update_data[field])
# Update genres if provided
if genre_ids is not None:
# Remove existing genres
db.query(MangaGenre).filter(MangaGenre.manga_id == db_obj.id).delete()
# Add new genres
for genre_id in genre_ids:
manga_genre = MangaGenre(manga_id=db_obj.id, genre_id=genre_id)
db.add(manga_genre)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
def search(
self,
db: Session,
*,
title: str | None = None,
author_id: int | None = None,
publisher_id: int | None = None,
genre_id: int | None = None,
in_stock: bool | None = None,
skip: int = 0,
limit: int = 100,
) -> list[Manga]:
"""
Search manga by various criteria.
"""
query = db.query(Manga)
if title:
query = query.filter(Manga.title.ilike(f"%{title}%"))
if author_id:
query = query.filter(Manga.author_id == author_id)
if publisher_id:
query = query.filter(Manga.publisher_id == publisher_id)
if genre_id:
query = query.join(Manga.genres).filter(MangaGenre.genre_id == genre_id)
if in_stock is not None:
query = query.filter(Manga.in_stock == in_stock)
return (
query.options(
joinedload(Manga.author),
joinedload(Manga.publisher),
joinedload(Manga.genres).joinedload(MangaGenre.genre),
)
.offset(skip)
.limit(limit)
.all()
)
manga = CRUDManga(Manga)

24
app/crud/publisher.py Normal file
View File

@ -0,0 +1,24 @@
from sqlalchemy.orm import Session
from app.crud.base import CRUDBase
from app.models.manga import Publisher
from app.schemas.publisher import PublisherCreate, PublisherUpdate
class CRUDPublisher(CRUDBase[Publisher, PublisherCreate, PublisherUpdate]):
def get_by_name(self, db: Session, *, name: str) -> Publisher | None:
"""
Get a publisher by name.
"""
return db.query(Publisher).filter(Publisher.name == name).first()
def get_multi_with_manga(
self, db: Session, *, skip: int = 0, limit: int = 100
) -> list[Publisher]:
"""
Get multiple publishers with their manga lists.
"""
return db.query(Publisher).offset(skip).limit(limit).all()
publisher = CRUDPublisher(Publisher)

0
app/db/__init__.py Normal file
View File

5
app/db/base.py Normal file
View File

@ -0,0 +1,5 @@
# Import all the models for Alembic to detect
from app.db.base_class import Base # noqa
# Import all models here for Alembic to detect them
from app.models.manga import Author, Genre, Manga, MangaGenre, Publisher # noqa

14
app/db/base_class.py Normal file
View File

@ -0,0 +1,14 @@
from typing import Any
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
id: Any
__name__: str
# Generate __tablename__ automatically
@declared_attr.directive
def __tablename__(self) -> str:
return self.__name__.lower()

13
app/db/session.py Normal file
View File

@ -0,0 +1,13 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create the directory for the SQLite database if it doesn't exist
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

0
app/models/__init__.py Normal file
View File

114
app/models/manga.py Normal file
View File

@ -0,0 +1,114 @@
from datetime import datetime
from sqlalchemy import Boolean, DateTime, Float, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base_class import Base
class Author(Base):
"""Author model for manga creators."""
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
name: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
biography: Mapped[str | None] = mapped_column(Text, nullable=True)
# Relationship with Manga
manga_list = relationship("Manga", back_populates="author")
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class Publisher(Base):
"""Publisher model for manga books."""
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
name: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
website: Mapped[str | None] = mapped_column(String(255), nullable=True)
country: Mapped[str | None] = mapped_column(String(50), nullable=True)
# Relationship with Manga
manga_list = relationship("Manga", back_populates="publisher")
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class Genre(Base):
"""Genre model for manga classification."""
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
name: Mapped[str] = mapped_column(String(50), nullable=False, index=True, unique=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
# Relationship with Manga
manga_list = relationship("MangaGenre", back_populates="genre")
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class Manga(Base):
"""Manga model representing a manga book in inventory."""
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
original_title: Mapped[str | None] = mapped_column(String(255), nullable=True)
isbn: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True, unique=True)
description: Mapped[str | None] = mapped_column(Text, nullable=True)
# Volume information
volume_number: Mapped[int | None] = mapped_column(Integer, nullable=True)
total_volumes: Mapped[int | None] = mapped_column(Integer, nullable=True)
# Foreign keys
author_id: Mapped[int | None] = mapped_column(Integer, ForeignKey("author.id"), nullable=True)
publisher_id: Mapped[int | None] = mapped_column(
Integer, ForeignKey("publisher.id"), nullable=True
)
# Relationships
author = relationship("Author", back_populates="manga_list")
publisher = relationship("Publisher", back_populates="manga_list")
genres = relationship("MangaGenre", back_populates="manga")
# Publication information
publication_date: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
# Physical attributes
page_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
# Inventory information
price: Mapped[float | None] = mapped_column(Float, nullable=True)
quantity: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
in_stock: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
# Ratings and metadata
rating: Mapped[float | None] = mapped_column(Float, nullable=True)
language: Mapped[str | None] = mapped_column(String(50), nullable=True)
cover_image_url: Mapped[str | None] = mapped_column(String(255), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
)
class MangaGenre(Base):
"""Junction table for many-to-many relationship between Manga and Genre."""
manga_id: Mapped[int] = mapped_column(Integer, ForeignKey("manga.id"), primary_key=True)
genre_id: Mapped[int] = mapped_column(Integer, ForeignKey("genre.id"), primary_key=True)
# Relationships
manga = relationship("Manga", back_populates="genres")
genre = relationship("Genre", back_populates="manga_list")
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)

32
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,32 @@
from app.schemas.author import Author, AuthorCreate, AuthorInDB, AuthorUpdate, AuthorWithManga
from app.schemas.genre import Genre, GenreCreate, GenreInDB, GenreUpdate
from app.schemas.manga import Manga, MangaCreate, MangaInDB, MangaUpdate, MangaWithRelations
from app.schemas.publisher import (
Publisher,
PublisherCreate,
PublisherInDB,
PublisherUpdate,
PublisherWithManga,
)
__all__ = [
"Author",
"AuthorCreate",
"AuthorInDB",
"AuthorUpdate",
"AuthorWithManga",
"Genre",
"GenreCreate",
"GenreInDB",
"GenreUpdate",
"Manga",
"MangaCreate",
"MangaInDB",
"MangaUpdate",
"MangaWithRelations",
"Publisher",
"PublisherCreate",
"PublisherInDB",
"PublisherUpdate",
"PublisherWithManga",
]

46
app/schemas/author.py Normal file
View File

@ -0,0 +1,46 @@
from datetime import datetime
from pydantic import BaseModel, Field
# Shared properties
class AuthorBase(BaseModel):
name: str = Field(..., min_length=1, max_length=100, description="Name of the author")
biography: str | None = Field(None, description="Author's biography")
# Properties to receive on author creation
class AuthorCreate(AuthorBase):
pass
# Properties to receive on author update
class AuthorUpdate(AuthorBase):
name: str | None = Field(None, min_length=1, max_length=100, description="Name of the author")
# Properties shared by models stored in DB
class AuthorInDBBase(AuthorBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
# Properties to return to client
class Author(AuthorInDBBase):
pass
# Properties properties stored in DB
class AuthorInDB(AuthorInDBBase):
pass
# Additional properties for response with manga list
class AuthorWithManga(Author):
from app.schemas.manga import Manga # Avoid circular import
manga_list: list[Manga] = []

39
app/schemas/genre.py Normal file
View File

@ -0,0 +1,39 @@
from datetime import datetime
from pydantic import BaseModel, Field
# Shared properties
class GenreBase(BaseModel):
name: str = Field(..., min_length=1, max_length=50, description="Name of the genre")
description: str | None = Field(None, description="Description of the genre")
# Properties to receive on genre creation
class GenreCreate(GenreBase):
pass
# Properties to receive on genre update
class GenreUpdate(GenreBase):
name: str | None = Field(None, min_length=1, max_length=50, description="Name of the genre")
# Properties shared by models stored in DB
class GenreInDBBase(GenreBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
# Properties to return to client
class Genre(GenreInDBBase):
pass
# Properties properties stored in DB
class GenreInDB(GenreInDBBase):
pass

80
app/schemas/manga.py Normal file
View File

@ -0,0 +1,80 @@
from datetime import datetime
from pydantic import BaseModel, Field, validator
from app.schemas.author import Author
from app.schemas.genre import Genre
from app.schemas.publisher import Publisher
# Shared properties
class MangaBase(BaseModel):
title: str = Field(..., min_length=1, max_length=255, description="Title of the manga")
original_title: str | None = Field(
None, max_length=255, description="Original title in Japanese or other language"
)
isbn: str | None = Field(None, max_length=20, description="ISBN of the manga volume")
description: str | None = Field(None, description="Description of the manga")
volume_number: int | None = Field(None, ge=1, description="Volume number in the series")
total_volumes: int | None = Field(
None, ge=1, description="Total number of volumes in the series"
)
publication_date: datetime | None = Field(None, description="Publication date of the manga")
page_count: int | None = Field(None, ge=1, description="Number of pages")
price: float | None = Field(None, ge=0, description="Price of the manga")
quantity: int = Field(0, ge=0, description="Quantity in inventory")
in_stock: bool = Field(True, description="Whether the manga is in stock")
rating: float | None = Field(None, ge=0, le=10, description="Rating of the manga (0-10)")
language: str | None = Field(None, max_length=50, description="Language of the manga")
cover_image_url: str | None = Field(None, max_length=255, description="URL to the cover image")
@validator("total_volumes")
def validate_total_volumes(self, v, values):
if v is not None and "volume_number" in values and values["volume_number"] is not None:
if v < values["volume_number"]:
raise ValueError("Total volumes must be greater than or equal to volume number")
return v
# Properties to receive on manga creation
class MangaCreate(MangaBase):
author_id: int | None = Field(None, description="ID of the author")
publisher_id: int | None = Field(None, description="ID of the publisher")
genre_ids: list[int] | None = Field(None, description="IDs of the genres")
# Properties to receive on manga update
class MangaUpdate(MangaBase):
title: str | None = Field(None, min_length=1, max_length=255, description="Title of the manga")
author_id: int | None = Field(None, description="ID of the author")
publisher_id: int | None = Field(None, description="ID of the publisher")
genre_ids: list[int] | None = Field(None, description="IDs of the genres")
# Properties shared by models stored in DB
class MangaInDBBase(MangaBase):
id: int
author_id: int | None
publisher_id: int | None
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
# Properties to return to client
class Manga(MangaInDBBase):
pass
# Properties properties stored in DB
class MangaInDB(MangaInDBBase):
pass
# Additional properties for response with relationships
class MangaWithRelations(Manga):
author: Author | None = None
publisher: Publisher | None = None
genres: list[Genre] = []

49
app/schemas/publisher.py Normal file
View File

@ -0,0 +1,49 @@
from datetime import datetime
from pydantic import BaseModel, Field
# Shared properties
class PublisherBase(BaseModel):
name: str = Field(..., min_length=1, max_length=100, description="Name of the publisher")
website: str | None = Field(None, description="Website URL of the publisher")
country: str | None = Field(None, max_length=50, description="Country of the publisher")
# Properties to receive on publisher creation
class PublisherCreate(PublisherBase):
pass
# Properties to receive on publisher update
class PublisherUpdate(PublisherBase):
name: str | None = Field(
None, min_length=1, max_length=100, description="Name of the publisher"
)
# Properties shared by models stored in DB
class PublisherInDBBase(PublisherBase):
id: int
created_at: datetime
updated_at: datetime
class Config:
orm_mode = True
# Properties to return to client
class Publisher(PublisherInDBBase):
pass
# Properties properties stored in DB
class PublisherInDB(PublisherInDBBase):
pass
# Additional properties for response with manga list
class PublisherWithManga(Publisher):
from app.schemas.manga import Manga # Avoid circular import
manga_list: list[Manga] = []

83
main.py Normal file
View File

@ -0,0 +1,83 @@
import time
from contextlib import asynccontextmanager
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger
from app.api.v1.api import api_router
from app.core.config import settings
from app.core.logging import setup_logging
@asynccontextmanager
async def lifespan(app: FastAPI):
"""
Context manager for FastAPI app lifespan events.
Startup and shutdown events run on application startup and shutdown.
"""
# Setup logging on startup
setup_logging()
logger.info(f"Starting up {settings.PROJECT_NAME}")
yield # Run the application
# Clean up resources on shutdown
logger.info(f"Shutting down {settings.PROJECT_NAME}")
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url="/openapi.json",
version=settings.VERSION,
lifespan=lifespan,
)
# Add middleware
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
"""
Middleware to add X-Process-Time header to response.
"""
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
# Log request details
logger.info(
f"{request.method} {request.url.path} "
f"Status: {response.status_code} "
f"Process Time: {process_time:.4f}s"
)
return response
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
@app.get("/health", tags=["health"])
async def health_check():
"""
Health check endpoint to verify the API is running.
"""
logger.debug("Health check endpoint called")
return {"status": "healthy"}
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

1
migrations/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration for Alembic.

80
migrations/env.py Normal file
View File

@ -0,0 +1,80 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
from app.db.base import Base # noqa
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
is_sqlite = connection.dialect.name == "sqlite"
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite, # Key configuration for SQLite
compare_type=True,
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()

26
migrations/script.py.mako Normal file
View File

@ -0,0 +1,26 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,131 @@
"""Initial tables
Revision ID: 01_initial_tables
Revises:
Create Date: 2023-11-10
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "01_initial_tables"
down_revision: str | None = None
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
# Create author table
op.create_table(
"author",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=100), nullable=False),
sa.Column("biography", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_author_id"), "author", ["id"], unique=False)
op.create_index(op.f("ix_author_name"), "author", ["name"], unique=False)
# Create publisher table
op.create_table(
"publisher",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=100), nullable=False),
sa.Column("website", sa.String(length=255), nullable=True),
sa.Column("country", sa.String(length=50), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_publisher_id"), "publisher", ["id"], unique=False)
op.create_index(op.f("ix_publisher_name"), "publisher", ["name"], unique=False)
# Create genre table
op.create_table(
"genre",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("name", sa.String(length=50), nullable=False),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_genre_id"), "genre", ["id"], unique=False)
op.create_index(op.f("ix_genre_name"), "genre", ["name"], unique=True)
# Create manga table
op.create_table(
"manga",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("title", sa.String(length=255), nullable=False),
sa.Column("original_title", sa.String(length=255), nullable=True),
sa.Column("isbn", sa.String(length=20), nullable=True),
sa.Column("description", sa.Text(), nullable=True),
sa.Column("volume_number", sa.Integer(), nullable=True),
sa.Column("total_volumes", sa.Integer(), nullable=True),
sa.Column("author_id", sa.Integer(), nullable=True),
sa.Column("publisher_id", sa.Integer(), nullable=True),
sa.Column("publication_date", sa.DateTime(), nullable=True),
sa.Column("page_count", sa.Integer(), nullable=True),
sa.Column("price", sa.Float(), nullable=True),
sa.Column("quantity", sa.Integer(), nullable=False, server_default="0"),
sa.Column("in_stock", sa.Boolean(), nullable=False, server_default="1"),
sa.Column("rating", sa.Float(), nullable=True),
sa.Column("language", sa.String(length=50), nullable=True),
sa.Column("cover_image_url", sa.String(length=255), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(
["author_id"],
["author.id"],
),
sa.ForeignKeyConstraint(
["publisher_id"],
["publisher.id"],
),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f("ix_manga_id"), "manga", ["id"], unique=False)
op.create_index(op.f("ix_manga_isbn"), "manga", ["isbn"], unique=True)
op.create_index(op.f("ix_manga_title"), "manga", ["title"], unique=False)
# Create manga_genre table (junction table)
op.create_table(
"manga_genre",
sa.Column("manga_id", sa.Integer(), nullable=False),
sa.Column("genre_id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(
["genre_id"],
["genre.id"],
),
sa.ForeignKeyConstraint(
["manga_id"],
["manga.id"],
),
sa.PrimaryKeyConstraint("manga_id", "genre_id"),
)
def downgrade() -> None:
# Drop tables in reverse order
op.drop_table("manga_genre")
op.drop_index(op.f("ix_manga_title"), table_name="manga")
op.drop_index(op.f("ix_manga_isbn"), table_name="manga")
op.drop_index(op.f("ix_manga_id"), table_name="manga")
op.drop_table("manga")
op.drop_index(op.f("ix_genre_name"), table_name="genre")
op.drop_index(op.f("ix_genre_id"), table_name="genre")
op.drop_table("genre")
op.drop_index(op.f("ix_publisher_name"), table_name="publisher")
op.drop_index(op.f("ix_publisher_id"), table_name="publisher")
op.drop_table("publisher")
op.drop_index(op.f("ix_author_name"), table_name="author")
op.drop_index(op.f("ix_author_id"), table_name="author")
op.drop_table("author")

26
pyproject.toml Normal file
View File

@ -0,0 +1,26 @@
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"F", # pyflakes
"I", # isort
"N", # pep8-naming
"UP", # pyupgrade
"YTT", # flake8-2020
]
ignore = [
"E203", # whitespace before ':'
"E501", # line too long
]
[tool.ruff.lint.isort]
known-third-party = ["fastapi", "pydantic", "sqlalchemy"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
line-ending = "auto"
skip-magic-trailing-comma = false

11
requirements.txt Normal file
View File

@ -0,0 +1,11 @@
fastapi>=0.104.1
uvicorn>=0.24.0
sqlalchemy>=2.0.23
pydantic>=2.4.2
pydantic-settings>=2.0.3
alembic>=1.12.1
python-dotenv>=1.0.0
python-multipart>=0.0.6
ruff>=0.1.5
email-validator>=2.1.0
loguru>=0.7.2