Update code via agent code generation
This commit is contained in:
parent
d9b773ed81
commit
5fb48b28e9
85
alembic.ini
Normal file
85
alembic.ini
Normal file
@ -0,0 +1,85 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration files
|
||||
# file_template = %%(rev)s_%%(slug)s
|
||||
|
||||
# timezone to use when rendering the date
|
||||
# within the migration file as well as the filename.
|
||||
# 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
|
||||
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# SQLite URL example
|
||||
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
|
||||
|
||||
# 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
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
7
app/api/v1/api.py
Normal file
7
app/api/v1/api.py
Normal file
@ -0,0 +1,7 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from app.api.v1 import health, inventory
|
||||
|
||||
api_router = APIRouter()
|
||||
api_router.include_router(health.router, prefix="/health", tags=["health"])
|
||||
api_router.include_router(inventory.router, prefix="/inventory", tags=["inventory"])
|
16
app/api/v1/health.py
Normal file
16
app/api/v1/health.py
Normal file
@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import get_db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("")
|
||||
def health_check(db: Session = Depends(get_db)):
|
||||
"""
|
||||
Health check endpoint that verifies API and database connection are working.
|
||||
"""
|
||||
# Simple db query to check database connection
|
||||
db.execute("SELECT 1")
|
||||
return {"status": "ok", "message": "API is operational"}
|
149
app/api/v1/inventory.py
Normal file
149
app/api/v1/inventory.py
Normal file
@ -0,0 +1,149 @@
|
||||
from typing import Any, List, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import get_db
|
||||
from app.models.inventory import Item as ItemModel
|
||||
from app.schemas.inventory import Item, ItemCreate, ItemList, ItemUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("", response_model=Item, status_code=status.HTTP_201_CREATED)
|
||||
def create_item(*, db: Session = Depends(get_db), item_in: ItemCreate) -> Any:
|
||||
"""
|
||||
Create a new inventory item.
|
||||
"""
|
||||
# Check if an item with the same SKU already exists (if SKU is provided)
|
||||
if item_in.sku:
|
||||
existing_item = db.query(ItemModel).filter(ItemModel.sku == item_in.sku).first()
|
||||
if existing_item:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Item with SKU {item_in.sku} already exists",
|
||||
)
|
||||
|
||||
try:
|
||||
db_item = ItemModel(**item_in.model_dump(exclude_unset=True))
|
||||
db.add(db_item)
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Could not create item. Check for duplicate SKU or invalid data.",
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=ItemList)
|
||||
def read_items(
|
||||
*,
|
||||
db: Session = Depends(get_db),
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
name: Optional[str] = None,
|
||||
category: Optional[str] = None,
|
||||
sku: Optional[str] = None,
|
||||
) -> Any:
|
||||
"""
|
||||
Retrieve inventory items with optional filtering.
|
||||
"""
|
||||
query = db.query(ItemModel)
|
||||
|
||||
# Apply filters if provided
|
||||
if name:
|
||||
query = query.filter(ItemModel.name.ilike(f"%{name}%"))
|
||||
if category:
|
||||
query = query.filter(ItemModel.category == category)
|
||||
if sku:
|
||||
query = query.filter(ItemModel.sku == sku)
|
||||
|
||||
# Get total count for pagination info
|
||||
total = query.count()
|
||||
|
||||
# Apply pagination
|
||||
items = query.order_by(ItemModel.name).offset(skip).limit(limit).all()
|
||||
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.get("/{item_id}", response_model=Item)
|
||||
def read_item(*, db: Session = Depends(get_db), item_id: int) -> Any:
|
||||
"""
|
||||
Get a specific inventory item by ID.
|
||||
"""
|
||||
item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
|
||||
if not item:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Item with ID {item_id} not found",
|
||||
)
|
||||
return item
|
||||
|
||||
|
||||
@router.put("/{item_id}", response_model=Item)
|
||||
def update_item(
|
||||
*, db: Session = Depends(get_db), item_id: int, item_in: ItemUpdate
|
||||
) -> Any:
|
||||
"""
|
||||
Update an existing inventory item.
|
||||
"""
|
||||
db_item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Item with ID {item_id} not found",
|
||||
)
|
||||
|
||||
# Check if there are any fields to update
|
||||
update_data = item_in.model_dump(exclude_unset=True)
|
||||
if not update_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="No fields to update were provided",
|
||||
)
|
||||
|
||||
# Check if SKU already exists when updating SKU
|
||||
if "sku" in update_data and update_data["sku"] and update_data["sku"] != db_item.sku:
|
||||
existing_item = db.query(ItemModel).filter(ItemModel.sku == update_data["sku"]).first()
|
||||
if existing_item:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"Item with SKU {update_data['sku']} already exists",
|
||||
)
|
||||
|
||||
try:
|
||||
for field, value in update_data.items():
|
||||
setattr(db_item, field, value)
|
||||
|
||||
db.add(db_item)
|
||||
db.commit()
|
||||
db.refresh(db_item)
|
||||
return db_item
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Could not update item. Check for duplicate SKU or invalid data.",
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||
def delete_item(*, db: Session = Depends(get_db), item_id: int) -> Any:
|
||||
"""
|
||||
Delete an inventory item.
|
||||
"""
|
||||
db_item = db.query(ItemModel).filter(ItemModel.id == item_id).first()
|
||||
if not db_item:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Item with ID {item_id} not found",
|
||||
)
|
||||
|
||||
db.delete(db_item)
|
||||
db.commit()
|
||||
return None
|
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
30
app/core/config.py
Normal file
30
app/core/config.py
Normal file
@ -0,0 +1,30 @@
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Union
|
||||
|
||||
from pydantic import AnyHttpUrl, validator
|
||||
from pydantic_settings import BaseSettings
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
API_V1_STR: str = "/api/v1"
|
||||
API_VERSION: str = "0.1.0"
|
||||
PROJECT_NAME: str = "Simple Inventory Manager API"
|
||||
|
||||
# CORS Configuration
|
||||
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||
|
||||
@validator("BACKEND_CORS_ORIGINS", pre=True)
|
||||
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[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"
|
||||
|
||||
|
||||
# Create global settings object
|
||||
settings = Settings()
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
||||
# Import all the models here so Alembic can discover them
|
||||
from app.db.base_class import Base # noqa
|
||||
from app.models.inventory import Item # noqa
|
14
app/db/base_class.py
Normal file
14
app/db/base_class.py
Normal file
@ -0,0 +1,14 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.ext.declarative import as_declarative, declared_attr
|
||||
|
||||
|
||||
@as_declarative()
|
||||
class Base:
|
||||
id: Any
|
||||
__name__: str
|
||||
|
||||
# Generate __tablename__ automatically based on class name
|
||||
@declared_attr
|
||||
def __tablename__(cls) -> str:
|
||||
return cls.__name__.lower()
|
28
app/db/session.py
Normal file
28
app/db/session.py
Normal file
@ -0,0 +1,28 @@
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
# Ensure the database directory exists
|
||||
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} # Needed for SQLite
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# Dependency to get DB session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
22
app/models/inventory.py
Normal file
22
app/models/inventory.py
Normal file
@ -0,0 +1,22 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import Column, DateTime, Float, Integer, String, Text
|
||||
|
||||
from app.db.base_class import Base
|
||||
|
||||
|
||||
class Item(Base):
|
||||
"""
|
||||
Database model for inventory items.
|
||||
"""
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(255), nullable=False, index=True)
|
||||
description = Column(Text, nullable=True)
|
||||
quantity = Column(Integer, nullable=False, default=0)
|
||||
unit_price = Column(Float, nullable=True)
|
||||
sku = Column(String(50), unique=True, index=True, nullable=True)
|
||||
category = Column(String(100), nullable=True, index=True)
|
||||
location = Column(String(100), nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.utcnow)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
8
app/schemas/__init__.py
Normal file
8
app/schemas/__init__.py
Normal file
@ -0,0 +1,8 @@
|
||||
from app.schemas.inventory import (
|
||||
ItemBase,
|
||||
ItemCreate,
|
||||
ItemUpdate,
|
||||
ItemInDB,
|
||||
Item,
|
||||
ItemList,
|
||||
)
|
60
app/schemas/inventory.py
Normal file
60
app/schemas/inventory.py
Normal file
@ -0,0 +1,60 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
class ItemBase(BaseModel):
|
||||
"""Base model with common attributes for an inventory item."""
|
||||
name: str = Field(..., description="Name of the inventory item", min_length=1, max_length=255)
|
||||
description: Optional[str] = Field(None, description="Detailed description of the item")
|
||||
quantity: int = Field(..., description="Current quantity in stock", ge=0)
|
||||
unit_price: Optional[float] = Field(None, description="Price per unit", ge=0)
|
||||
sku: Optional[str] = Field(None, description="Stock Keeping Unit - unique identifier", max_length=50)
|
||||
category: Optional[str] = Field(None, description="Category the item belongs to", max_length=100)
|
||||
location: Optional[str] = Field(None, description="Storage location of the item", max_length=100)
|
||||
|
||||
|
||||
class ItemCreate(ItemBase):
|
||||
"""Schema for creating a new inventory item."""
|
||||
pass
|
||||
|
||||
|
||||
class ItemUpdate(BaseModel):
|
||||
"""Schema for updating an existing inventory item - all fields are optional."""
|
||||
name: Optional[str] = Field(None, description="Name of the inventory item", min_length=1, max_length=255)
|
||||
description: Optional[str] = Field(None, description="Detailed description of the item")
|
||||
quantity: Optional[int] = Field(None, description="Current quantity in stock", ge=0)
|
||||
unit_price: Optional[float] = Field(None, description="Price per unit", ge=0)
|
||||
sku: Optional[str] = Field(None, description="Stock Keeping Unit - unique identifier", max_length=50)
|
||||
category: Optional[str] = Field(None, description="Category the item belongs to", max_length=100)
|
||||
location: Optional[str] = Field(None, description="Storage location of the item", max_length=100)
|
||||
|
||||
@validator("*", pre=True)
|
||||
def check_none_fields(cls, v):
|
||||
"""Make sure at least one field is not None to perform an update"""
|
||||
return v
|
||||
|
||||
class Config:
|
||||
extra = "forbid"
|
||||
|
||||
|
||||
class ItemInDB(ItemBase):
|
||||
"""Schema for an inventory item as stored in the database."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class Item(ItemInDB):
|
||||
"""Schema for returning an inventory item."""
|
||||
pass
|
||||
|
||||
|
||||
class ItemList(BaseModel):
|
||||
"""Schema for returning a list of inventory items."""
|
||||
items: List[Item]
|
||||
total: int
|
44
main.py
Normal file
44
main.py
Normal file
@ -0,0 +1,44 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
|
||||
from app.api.v1.api import api_router
|
||||
from app.core.config import settings
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.PROJECT_NAME,
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
return app.openapi_schema
|
||||
openapi_schema = get_openapi(
|
||||
title=settings.PROJECT_NAME,
|
||||
version=settings.API_VERSION,
|
||||
description="Simple Inventory Manager API",
|
||||
routes=app.routes,
|
||||
)
|
||||
app.openapi_schema = openapi_schema
|
||||
return app.openapi_schema
|
||||
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
82
migrations/env.py
Normal file
82
migrations/env.py
Normal file
@ -0,0 +1,82 @@
|
||||
import os
|
||||
from logging.config import fileConfig
|
||||
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
|
||||
# Import Base metadata from app
|
||||
from app.db.base import Base
|
||||
|
||||
# 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
|
||||
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"},
|
||||
render_as_batch=True, # SQLite needs this for migrations that alter tables
|
||||
)
|
||||
|
||||
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, # SQLite needs this for migrations that alter tables
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/script.py.mako
Normal file
@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
${downgrades if downgrades else "pass"}
|
9
requirements.txt
Normal file
9
requirements.txt
Normal file
@ -0,0 +1,9 @@
|
||||
fastapi>=0.100.0
|
||||
uvicorn>=0.22.0
|
||||
sqlalchemy>=2.0.0
|
||||
alembic>=1.11.0
|
||||
pydantic>=2.0.0
|
||||
pydantic-settings>=2.0.0
|
||||
python-dotenv>=1.0.0
|
||||
email-validator>=2.0.0
|
||||
ruff>=0.1.0
|
Loading…
x
Reference in New Issue
Block a user