Pipelinen parannuksia building blockeilla

This commit is contained in:
Jaakko Vanhala
2026-04-12 18:48:14 +03:00
parent c1a5f8aff5
commit b2ee8b9031
175 changed files with 13311 additions and 237 deletions

View File

@@ -0,0 +1,11 @@
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
ENV UV_CACHE_DIR=/tmp/uv-cache
WORKDIR /app
COPY pyproject.toml .
RUN uv sync
COPY *.py .
RUN useradd -m appuser && chown -R appuser:appuser /app /tmp/uv-cache
USER appuser
EXPOSE 8000
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

View File

@@ -0,0 +1,5 @@
services:
app:
build: .
ports:
- "18765:8000"

View File

@@ -0,0 +1,127 @@
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from models import Base, engine, SessionLocal, User, Article, Comment
from schemas import UserCreate, ArticleCreate, CommentCreate, UserResponse, ArticleResponse, CommentResponse
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/users/", response_model=UserResponse, status_code=201)
def create_user(item: UserCreate, db: Session = Depends(get_db)):
db_item = User(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/users/", response_model=list[UserResponse])
def list_users(db: Session = Depends(get_db)):
return db.query(User).all()
@app.get("/users/{item_id}", response_model=UserResponse)
def get_user(item_id: int, db: Session = Depends(get_db)):
item = db.query(User).filter(User.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="User not found")
return item
@app.put("/users/{item_id}", response_model=UserResponse)
def update_user(item_id: int, item: UserCreate, db: Session = Depends(get_db)):
db_item = db.query(User).filter(User.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="User not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/users/{item_id}", status_code=204)
def delete_user(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(User).filter(User.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="User not found")
db.delete(db_item)
db.commit()
@app.post("/articles/", response_model=ArticleResponse, status_code=201)
def create_article(item: ArticleCreate, db: Session = Depends(get_db)):
db_item = Article(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/articles/", response_model=list[ArticleResponse])
def list_articles(db: Session = Depends(get_db)):
return db.query(Article).all()
@app.get("/articles/{item_id}", response_model=ArticleResponse)
def get_article(item_id: int, db: Session = Depends(get_db)):
item = db.query(Article).filter(Article.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Article not found")
return item
@app.put("/articles/{item_id}", response_model=ArticleResponse)
def update_article(item_id: int, item: ArticleCreate, db: Session = Depends(get_db)):
db_item = db.query(Article).filter(Article.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Article not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/articles/{item_id}", status_code=204)
def delete_article(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Article).filter(Article.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Article not found")
db.delete(db_item)
db.commit()
@app.post("/comments/", response_model=CommentResponse, status_code=201)
def create_comment(item: CommentCreate, db: Session = Depends(get_db)):
db_item = Comment(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/comments/", response_model=list[CommentResponse])
def list_comments(db: Session = Depends(get_db)):
return db.query(Comment).all()
@app.get("/comments/{item_id}", response_model=CommentResponse)
def get_comment(item_id: int, db: Session = Depends(get_db)):
item = db.query(Comment).filter(Comment.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Comment not found")
return item
@app.put("/comments/{item_id}", response_model=CommentResponse)
def update_comment(item_id: int, item: CommentCreate, db: Session = Depends(get_db)):
db_item = db.query(Comment).filter(Comment.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Comment not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/comments/{item_id}", status_code=204)
def delete_comment(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Comment).filter(Comment.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Comment not found")
db.delete(db_item)
db.commit()

View File

@@ -0,0 +1,31 @@
from sqlalchemy import create_engine, Column, Integer, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./app.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String(255), nullable=False)
email = Column(String(255), nullable=False)
password_hash = Column(Text, nullable=False)
class Article(Base):
__tablename__ = "articles"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False)
content = Column(Text, nullable=False)
author_id = Column(Integer, nullable=False)
class Comment(Base):
__tablename__ = "comments"
id = Column(Integer, primary_key=True, index=True)
content = Column(Text, nullable=False)
article_id = Column(Integer, nullable=False)
author_id = Column(Integer, nullable=False)
Base.metadata.create_all(bind=engine)

View File

@@ -0,0 +1,11 @@
[project]
name = "blogialusta"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"fastapi",
"uvicorn[standard]",
"sqlalchemy",
"pytest",
"httpx",
]

View File

@@ -0,0 +1,110 @@
{
"run_id": "tmpl_blog",
"model": "qwen2.5-coder:7b-instruct-q4_K_M",
"description": "Blogialusta: käyttäjät voivat luoda artikkeleita ja kommentoida",
"spec": {
"project_name": "blogialusta",
"description": "A blogging platform where users can create articles and comment on them.",
"entities": [
{
"name": "User",
"table_name": "users",
"fields": [
{
"name": "username",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "email",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "password_hash",
"sa_type": "Text",
"py_type": "str",
"nullable": false,
"default": null
}
]
},
{
"name": "Article",
"table_name": "articles",
"fields": [
{
"name": "title",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "content",
"sa_type": "Text",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "author_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
}
]
},
{
"name": "Comment",
"table_name": "comments",
"fields": [
{
"name": "content",
"sa_type": "Text",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "article_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "author_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
}
]
}
],
"extra_imports": [
"from datetime import date"
]
},
"files": {
"models.py": 1175,
"schemas.py": 613,
"main.py": 4781,
"test_main.py": 5488,
"pyproject.toml": 180,
"Dockerfile": 339
},
"valid": true,
"docker": {
"build": true,
"pytest": true,
"api": true,
"errors": []
}
}

View File

@@ -0,0 +1,35 @@
from pydantic import BaseModel
from datetime import date
class UserCreate(BaseModel):
username: str
email: str
password_hash: str
class UserResponse(UserCreate):
id: int
class Config:
from_attributes = True
class ArticleCreate(BaseModel):
title: str
content: str
author_id: int
class ArticleResponse(ArticleCreate):
id: int
class Config:
from_attributes = True
class CommentCreate(BaseModel):
content: str
article_id: int
author_id: int
class CommentResponse(CommentCreate):
id: int
class Config:
from_attributes = True

View File

@@ -0,0 +1,90 @@
{
"project_name": "blogialusta",
"description": "A blogging platform where users can create articles and comment on them.",
"entities": [
{
"name": "User",
"table_name": "users",
"fields": [
{
"name": "username",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "email",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "password_hash",
"sa_type": "Text",
"py_type": "str",
"nullable": false,
"default": null
}
]
},
{
"name": "Article",
"table_name": "articles",
"fields": [
{
"name": "title",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "content",
"sa_type": "Text",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "author_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
}
]
},
{
"name": "Comment",
"table_name": "comments",
"fields": [
{
"name": "content",
"sa_type": "Text",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "article_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "author_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
}
]
}
],
"extra_imports": [
"from datetime import date"
]
}

View File

@@ -0,0 +1,132 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, get_db
from models import Base
TEST_DB = "sqlite:///./test.db"
test_engine = create_engine(TEST_DB, connect_args={"check_same_thread": False})
TestSession = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
Base.metadata.create_all(bind=test_engine)
def override_get_db():
db = TestSession()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_create_user():
response = client.post('/users/', json={"username": "Test username", "email": "Test email", "password_hash": "Test password_hash"})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_users():
client.post('/users/', json={"username": "Test username", "email": "Test email", "password_hash": "Test password_hash"})
response = client.get('/users/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_user_by_id():
created = client.post('/users/', json={"username": "Test username", "email": "Test email", "password_hash": "Test password_hash"}).json()
item_id = created['id']
response = client.get(f'/users/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_user_not_found():
response = client.get('/users/99999')
assert response.status_code == 404
def test_update_user():
created = client.post('/users/', json={"username": "Test username", "email": "Test email", "password_hash": "Test password_hash"}).json()
item_id = created['id']
response = client.put(f'/users/{item_id}', json={"username": "Updated username", "email": "Test email", "password_hash": "Test password_hash"})
assert response.status_code == 200
def test_delete_user():
created = client.post('/users/', json={"username": "Test username", "email": "Test email", "password_hash": "Test password_hash"}).json()
item_id = created['id']
response = client.delete(f'/users/{item_id}')
assert response.status_code == 204
response = client.get(f'/users/{item_id}')
assert response.status_code == 404
def test_create_article():
response = client.post('/articles/', json={"title": "Test title", "content": "Test content", "author_id": 1})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_articles():
client.post('/articles/', json={"title": "Test title", "content": "Test content", "author_id": 1})
response = client.get('/articles/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_article_by_id():
created = client.post('/articles/', json={"title": "Test title", "content": "Test content", "author_id": 1}).json()
item_id = created['id']
response = client.get(f'/articles/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_article_not_found():
response = client.get('/articles/99999')
assert response.status_code == 404
def test_update_article():
created = client.post('/articles/', json={"title": "Test title", "content": "Test content", "author_id": 1}).json()
item_id = created['id']
response = client.put(f'/articles/{item_id}', json={"title": "Updated title", "content": "Test content", "author_id": 1})
assert response.status_code == 200
def test_delete_article():
created = client.post('/articles/', json={"title": "Test title", "content": "Test content", "author_id": 1}).json()
item_id = created['id']
response = client.delete(f'/articles/{item_id}')
assert response.status_code == 204
response = client.get(f'/articles/{item_id}')
assert response.status_code == 404
def test_create_comment():
response = client.post('/comments/', json={"content": "Test content", "article_id": 1, "author_id": 1})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_comments():
client.post('/comments/', json={"content": "Test content", "article_id": 1, "author_id": 1})
response = client.get('/comments/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_comment_by_id():
created = client.post('/comments/', json={"content": "Test content", "article_id": 1, "author_id": 1}).json()
item_id = created['id']
response = client.get(f'/comments/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_comment_not_found():
response = client.get('/comments/99999')
assert response.status_code == 404
def test_update_comment():
created = client.post('/comments/', json={"content": "Test content", "article_id": 1, "author_id": 1}).json()
item_id = created['id']
response = client.put(f'/comments/{item_id}', json={"content": "Updated content", "article_id": 1, "author_id": 1})
assert response.status_code == 200
def test_delete_comment():
created = client.post('/comments/', json={"content": "Test content", "article_id": 1, "author_id": 1}).json()
item_id = created['id']
response = client.delete(f'/comments/{item_id}')
assert response.status_code == 204
response = client.get(f'/comments/{item_id}')
assert response.status_code == 404

View File

@@ -0,0 +1,11 @@
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
ENV UV_CACHE_DIR=/tmp/uv-cache
WORKDIR /app
COPY pyproject.toml .
RUN uv sync
COPY *.py .
RUN useradd -m appuser && chown -R appuser:appuser /app /tmp/uv-cache
USER appuser
EXPOSE 8000
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

View File

@@ -0,0 +1,5 @@
services:
app:
build: .
ports:
- "18765:8000"

View File

@@ -0,0 +1,127 @@
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from models import Base, engine, SessionLocal, Product, StorageLocation, Transfer
from schemas import ProductCreate, StorageLocationCreate, TransferCreate, ProductResponse, StorageLocationResponse, TransferResponse
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/products/", response_model=ProductResponse, status_code=201)
def create_product(item: ProductCreate, db: Session = Depends(get_db)):
db_item = Product(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/products/", response_model=list[ProductResponse])
def list_products(db: Session = Depends(get_db)):
return db.query(Product).all()
@app.get("/products/{item_id}", response_model=ProductResponse)
def get_product(item_id: int, db: Session = Depends(get_db)):
item = db.query(Product).filter(Product.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Product not found")
return item
@app.put("/products/{item_id}", response_model=ProductResponse)
def update_product(item_id: int, item: ProductCreate, db: Session = Depends(get_db)):
db_item = db.query(Product).filter(Product.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Product not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/products/{item_id}", status_code=204)
def delete_product(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Product).filter(Product.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Product not found")
db.delete(db_item)
db.commit()
@app.post("/storage_locations/", response_model=StorageLocationResponse, status_code=201)
def create_storagelocation(item: StorageLocationCreate, db: Session = Depends(get_db)):
db_item = StorageLocation(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/storage_locations/", response_model=list[StorageLocationResponse])
def list_storagelocations(db: Session = Depends(get_db)):
return db.query(StorageLocation).all()
@app.get("/storage_locations/{item_id}", response_model=StorageLocationResponse)
def get_storagelocation(item_id: int, db: Session = Depends(get_db)):
item = db.query(StorageLocation).filter(StorageLocation.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="StorageLocation not found")
return item
@app.put("/storage_locations/{item_id}", response_model=StorageLocationResponse)
def update_storagelocation(item_id: int, item: StorageLocationCreate, db: Session = Depends(get_db)):
db_item = db.query(StorageLocation).filter(StorageLocation.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="StorageLocation not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/storage_locations/{item_id}", status_code=204)
def delete_storagelocation(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(StorageLocation).filter(StorageLocation.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="StorageLocation not found")
db.delete(db_item)
db.commit()
@app.post("/transfers/", response_model=TransferResponse, status_code=201)
def create_transfer(item: TransferCreate, db: Session = Depends(get_db)):
db_item = Transfer(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/transfers/", response_model=list[TransferResponse])
def list_transfers(db: Session = Depends(get_db)):
return db.query(Transfer).all()
@app.get("/transfers/{item_id}", response_model=TransferResponse)
def get_transfer(item_id: int, db: Session = Depends(get_db)):
item = db.query(Transfer).filter(Transfer.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Transfer not found")
return item
@app.put("/transfers/{item_id}", response_model=TransferResponse)
def update_transfer(item_id: int, item: TransferCreate, db: Session = Depends(get_db)):
db_item = db.query(Transfer).filter(Transfer.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Transfer not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/transfers/{item_id}", status_code=204)
def delete_transfer(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Transfer).filter(Transfer.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Transfer not found")
db.delete(db_item)
db.commit()

View File

@@ -0,0 +1,34 @@
from sqlalchemy import create_engine, Column, Integer, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./app.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Product(Base):
__tablename__ = "products"
id = Column(Integer, primary_key=True, index=True)
product_id = Column(Integer, nullable=False)
name = Column(String(255), nullable=False)
description = Column(Text)
category = Column(String(50), nullable=False)
class StorageLocation(Base):
__tablename__ = "storage_locations"
id = Column(Integer, primary_key=True, index=True)
location_id = Column(Integer, nullable=False)
name = Column(String(255), nullable=False)
capacity = Column(Integer, nullable=False, default=0)
class Transfer(Base):
__tablename__ = "transfers"
id = Column(Integer, primary_key=True, index=True)
transfer_id = Column(Integer, nullable=False)
product_id = Column(Integer, nullable=False)
from_location_id = Column(Integer, nullable=False)
to_location_id = Column(Integer, nullable=False)
quantity = Column(Integer, nullable=False, default=0)
Base.metadata.create_all(bind=engine)

View File

@@ -0,0 +1,11 @@
[project]
name = "warehouse_management"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"fastapi",
"uvicorn[standard]",
"sqlalchemy",
"pytest",
"httpx",
]

View File

@@ -0,0 +1,131 @@
{
"run_id": "tmpl_inventory",
"model": "qwen2.5-coder:7b-instruct-q4_K_M",
"description": "Varastonhallinta: tuotteet, varastot, siirrot varastojen välillä",
"spec": {
"project_name": "warehouse_management",
"description": "A system for managing warehouse operations including products, storage locations, and transfers between locations.",
"entities": [
{
"name": "Product",
"table_name": "products",
"fields": [
{
"name": "product_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "name",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "description",
"sa_type": "Text",
"py_type": "str | None",
"nullable": true,
"default": null
},
{
"name": "category",
"sa_type": "String(50)",
"py_type": "str",
"nullable": false,
"default": null
}
]
},
{
"name": "StorageLocation",
"table_name": "storage_locations",
"fields": [
{
"name": "location_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "name",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "capacity",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": 0
}
]
},
{
"name": "Transfer",
"table_name": "transfers",
"fields": [
{
"name": "transfer_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "product_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "from_location_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "to_location_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "quantity",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": 0
}
]
}
],
"extra_imports": [
"from datetime import date"
]
},
"files": {
"models.py": 1370,
"schemas.py": 743,
"main.py": 5146,
"test_main.py": 5898,
"pyproject.toml": 189,
"Dockerfile": 339
},
"valid": true,
"docker": {
"build": true,
"pytest": true,
"api": true,
"errors": []
}
}

View File

@@ -0,0 +1,38 @@
from pydantic import BaseModel
from datetime import date
class ProductCreate(BaseModel):
product_id: int
name: str
description: str | None = None
category: str
class ProductResponse(ProductCreate):
id: int
class Config:
from_attributes = True
class StorageLocationCreate(BaseModel):
location_id: int
name: str
capacity: int = 0
class StorageLocationResponse(StorageLocationCreate):
id: int
class Config:
from_attributes = True
class TransferCreate(BaseModel):
transfer_id: int
product_id: int
from_location_id: int
to_location_id: int
quantity: int = 0
class TransferResponse(TransferCreate):
id: int
class Config:
from_attributes = True

View File

@@ -0,0 +1,111 @@
{
"project_name": "warehouse_management",
"description": "A system for managing warehouse operations including products, storage locations, and transfers between locations.",
"entities": [
{
"name": "Product",
"table_name": "products",
"fields": [
{
"name": "product_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "name",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "description",
"sa_type": "Text",
"py_type": "str | None",
"nullable": true,
"default": null
},
{
"name": "category",
"sa_type": "String(50)",
"py_type": "str",
"nullable": false,
"default": null
}
]
},
{
"name": "StorageLocation",
"table_name": "storage_locations",
"fields": [
{
"name": "location_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "name",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "capacity",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": 0
}
]
},
{
"name": "Transfer",
"table_name": "transfers",
"fields": [
{
"name": "transfer_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "product_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "from_location_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "to_location_id",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": null
},
{
"name": "quantity",
"sa_type": "Integer",
"py_type": "int",
"nullable": false,
"default": 0
}
]
}
],
"extra_imports": [
"from datetime import date"
]
}

View File

@@ -0,0 +1,132 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, get_db
from models import Base
TEST_DB = "sqlite:///./test.db"
test_engine = create_engine(TEST_DB, connect_args={"check_same_thread": False})
TestSession = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
Base.metadata.create_all(bind=test_engine)
def override_get_db():
db = TestSession()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_create_product():
response = client.post('/products/', json={"product_id": 1, "name": "Test name", "description": "Test description", "category": "Test category"})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_products():
client.post('/products/', json={"product_id": 1, "name": "Test name", "description": "Test description", "category": "Test category"})
response = client.get('/products/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_product_by_id():
created = client.post('/products/', json={"product_id": 1, "name": "Test name", "description": "Test description", "category": "Test category"}).json()
item_id = created['id']
response = client.get(f'/products/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_product_not_found():
response = client.get('/products/99999')
assert response.status_code == 404
def test_update_product():
created = client.post('/products/', json={"product_id": 1, "name": "Test name", "description": "Test description", "category": "Test category"}).json()
item_id = created['id']
response = client.put(f'/products/{item_id}', json={"product_id": 1, "name": "Updated name", "description": "Test description", "category": "Test category"})
assert response.status_code == 200
def test_delete_product():
created = client.post('/products/', json={"product_id": 1, "name": "Test name", "description": "Test description", "category": "Test category"}).json()
item_id = created['id']
response = client.delete(f'/products/{item_id}')
assert response.status_code == 204
response = client.get(f'/products/{item_id}')
assert response.status_code == 404
def test_create_storagelocation():
response = client.post('/storage_locations/', json={"location_id": 1, "name": "Test name", "capacity": 0})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_storagelocations():
client.post('/storage_locations/', json={"location_id": 1, "name": "Test name", "capacity": 0})
response = client.get('/storage_locations/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_storagelocation_by_id():
created = client.post('/storage_locations/', json={"location_id": 1, "name": "Test name", "capacity": 0}).json()
item_id = created['id']
response = client.get(f'/storage_locations/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_storagelocation_not_found():
response = client.get('/storage_locations/99999')
assert response.status_code == 404
def test_update_storagelocation():
created = client.post('/storage_locations/', json={"location_id": 1, "name": "Test name", "capacity": 0}).json()
item_id = created['id']
response = client.put(f'/storage_locations/{item_id}', json={"location_id": 1, "name": "Updated name", "capacity": 0})
assert response.status_code == 200
def test_delete_storagelocation():
created = client.post('/storage_locations/', json={"location_id": 1, "name": "Test name", "capacity": 0}).json()
item_id = created['id']
response = client.delete(f'/storage_locations/{item_id}')
assert response.status_code == 204
response = client.get(f'/storage_locations/{item_id}')
assert response.status_code == 404
def test_create_transfer():
response = client.post('/transfers/', json={"transfer_id": 1, "product_id": 1, "from_location_id": 1, "to_location_id": 1, "quantity": 0})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_transfers():
client.post('/transfers/', json={"transfer_id": 1, "product_id": 1, "from_location_id": 1, "to_location_id": 1, "quantity": 0})
response = client.get('/transfers/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_transfer_by_id():
created = client.post('/transfers/', json={"transfer_id": 1, "product_id": 1, "from_location_id": 1, "to_location_id": 1, "quantity": 0}).json()
item_id = created['id']
response = client.get(f'/transfers/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_transfer_not_found():
response = client.get('/transfers/99999')
assert response.status_code == 404
def test_update_transfer():
created = client.post('/transfers/', json={"transfer_id": 1, "product_id": 1, "from_location_id": 1, "to_location_id": 1, "quantity": 0}).json()
item_id = created['id']
response = client.put(f'/transfers/{item_id}', json={"transfer_id": 1, "product_id": 1, "from_location_id": 1, "to_location_id": 1, "quantity": 0})
assert response.status_code == 200
def test_delete_transfer():
created = client.post('/transfers/', json={"transfer_id": 1, "product_id": 1, "from_location_id": 1, "to_location_id": 1, "quantity": 0}).json()
item_id = created['id']
response = client.delete(f'/transfers/{item_id}')
assert response.status_code == 204
response = client.get(f'/transfers/{item_id}')
assert response.status_code == 404

View File

@@ -0,0 +1,11 @@
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
ENV UV_CACHE_DIR=/tmp/uv-cache
WORKDIR /app
COPY pyproject.toml .
RUN uv sync
COPY *.py .
RUN useradd -m appuser && chown -R appuser:appuser /app /tmp/uv-cache
USER appuser
EXPOSE 8000
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

View File

@@ -0,0 +1,5 @@
services:
app:
build: .
ports:
- "18765:8000"

View File

@@ -0,0 +1,51 @@
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from models import Base, engine, SessionLocal, Todo
from schemas import TodoCreate, TodoResponse
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/todos/", response_model=TodoResponse, status_code=201)
def create_todo(item: TodoCreate, db: Session = Depends(get_db)):
db_item = Todo(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/todos/", response_model=list[TodoResponse])
def list_todos(db: Session = Depends(get_db)):
return db.query(Todo).all()
@app.get("/todos/{item_id}", response_model=TodoResponse)
def get_todo(item_id: int, db: Session = Depends(get_db)):
item = db.query(Todo).filter(Todo.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Todo not found")
return item
@app.put("/todos/{item_id}", response_model=TodoResponse)
def update_todo(item_id: int, item: TodoCreate, db: Session = Depends(get_db)):
db_item = db.query(Todo).filter(Todo.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Todo not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/todos/{item_id}", status_code=204)
def delete_todo(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Todo).filter(Todo.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(db_item)
db.commit()

View File

@@ -0,0 +1,18 @@
from sqlalchemy import create_engine, Column, Integer, Date, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./app.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False)
description = Column(Text)
due_date = Column(Date)
status = Column(String(20), nullable=False, default="pending")
Base.metadata.create_all(bind=engine)

View File

@@ -0,0 +1,11 @@
[project]
name = "todo-app"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"fastapi",
"uvicorn[standard]",
"sqlalchemy",
"pytest",
"httpx",
]

View File

@@ -0,0 +1,65 @@
{
"run_id": "tmpl_v1",
"model": "qwen2.5-coder:7b-instruct-q4_K_M",
"description": "Todo-sovellus FastAPI + SQLite, CRUD-endpointit ja testit",
"spec": {
"project_name": "todo-app",
"description": "A simple Todo application with CRUD endpoints using FastAPI and SQLite.",
"entities": [
{
"name": "Todo",
"table_name": "todos",
"fields": [
{
"name": "title",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "description",
"sa_type": "Text",
"py_type": "str | None",
"nullable": true,
"default": null
},
{
"name": "due_date",
"sa_type": "Date",
"py_type": "date | None",
"nullable": true,
"default": null
},
{
"name": "status",
"sa_type": "String(20)",
"py_type": "str",
"nullable": false,
"default": "pending"
}
]
}
],
"extra_imports": [
"from datetime import date"
]
},
"files": {
"models.py": 712,
"schemas.py": 293,
"main.py": 1711,
"test_main.py": 2439,
"pyproject.toml": 177,
"Dockerfile": 339
},
"valid": true,
"docker": {
"build": true,
"pytest": false,
"api": true,
"errors": [
"pytest exit 1:\nCreate):\n\n-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\n=========================== short test summary info ============================\nFAILED test_main.py::test_create_todo - sqlalchemy.exc.OperationalError: (sql...\nFAILED test_main.py::test_list_todos - sqlalchemy.exc.OperationalError: (sqli...\nFAILED test_main.py::test_get_todo_by_id - sqlalchemy.exc.OperationalError: (...\nFAILED test_main.py::test_get_todo_not_found - sqlalchemy.exc.OperationalErro...\nFAILED test_main.py::test_update_todo - sqlalchemy.exc.OperationalError: (sql...\nFAILED test_main.py::test_delete_todo - sqlalchemy.exc.OperationalError: (sql...\n======================== 6 failed, 2 warnings in 2.54s =========================\n Network tmpl_v1_default Creating\n Network tmpl_v1_default Created\n\n"
]
}
}

View File

@@ -0,0 +1,14 @@
from pydantic import BaseModel
from datetime import date
class TodoCreate(BaseModel):
title: str
description: str | None = None
due_date: date | None = None
status: str = "pending"
class TodoResponse(TodoCreate):
id: int
class Config:
from_attributes = True

View File

@@ -0,0 +1,43 @@
{
"project_name": "todo-app",
"description": "A simple Todo application with CRUD endpoints using FastAPI and SQLite.",
"entities": [
{
"name": "Todo",
"table_name": "todos",
"fields": [
{
"name": "title",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "description",
"sa_type": "Text",
"py_type": "str | None",
"nullable": true,
"default": null
},
{
"name": "due_date",
"sa_type": "Date",
"py_type": "date | None",
"nullable": true,
"default": null
},
{
"name": "status",
"sa_type": "String(20)",
"py_type": "str",
"nullable": false,
"default": "pending"
}
]
}
],
"extra_imports": [
"from datetime import date"
]
}

View File

@@ -0,0 +1,59 @@
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, get_db
from models import Base
engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False})
TestSession = sessionmaker(bind=engine)
def override_get_db():
db = TestSession()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def setup_function():
"""Luo taulut ennen jokaista testiä."""
Base.metadata.create_all(bind=engine)
def teardown_function():
"""Tyhjennä taulut jokaisen testin jälkeen."""
Base.metadata.drop_all(bind=engine)
def test_create_todo():
response = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
assert response.status_code == 201
assert response.json()["id"] is not None
def test_list_todos():
client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
response = client.get('/todos/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_todo_by_id():
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
response = client.get(f"/todos/{created["id"]}")
assert response.status_code == 200
assert response.json()["id"] == created["id"]
def test_get_todo_not_found():
response = client.get('/todos/99999')
assert response.status_code == 404
def test_update_todo():
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
response = client.put(f"/todos/{created["id"]}", json={"title": "Updated title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
assert response.status_code == 200
def test_delete_todo():
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
response = client.delete(f"/todos/{created["id"]}")
assert response.status_code == 204
response = client.get(f"/todos/{created["id"]}")
assert response.status_code == 404

View File

@@ -0,0 +1,11 @@
FROM python:3.12-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
ENV UV_CACHE_DIR=/tmp/uv-cache
WORKDIR /app
COPY pyproject.toml .
RUN uv sync
COPY *.py .
RUN useradd -m appuser && chown -R appuser:appuser /app /tmp/uv-cache
USER appuser
EXPOSE 8000
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

View File

@@ -0,0 +1,5 @@
services:
app:
build: .
ports:
- "18765:8000"

View File

@@ -0,0 +1,51 @@
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from models import Base, engine, SessionLocal, Todo
from schemas import TodoCreate, TodoResponse
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/todos/", response_model=TodoResponse, status_code=201)
def create_todo(item: TodoCreate, db: Session = Depends(get_db)):
db_item = Todo(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@app.get("/todos/", response_model=list[TodoResponse])
def list_todos(db: Session = Depends(get_db)):
return db.query(Todo).all()
@app.get("/todos/{item_id}", response_model=TodoResponse)
def get_todo(item_id: int, db: Session = Depends(get_db)):
item = db.query(Todo).filter(Todo.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Todo not found")
return item
@app.put("/todos/{item_id}", response_model=TodoResponse)
def update_todo(item_id: int, item: TodoCreate, db: Session = Depends(get_db)):
db_item = db.query(Todo).filter(Todo.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Todo not found")
for key, value in item.model_dump().items():
setattr(db_item, key, value)
db.commit()
db.refresh(db_item)
return db_item
@app.delete("/todos/{item_id}", status_code=204)
def delete_todo(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Todo).filter(Todo.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Todo not found")
db.delete(db_item)
db.commit()

View File

@@ -0,0 +1,18 @@
from sqlalchemy import create_engine, Column, Integer, Date, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./app.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False)
description = Column(Text)
due_date = Column(Date)
status = Column(String(20), nullable=False, default="pending")
Base.metadata.create_all(bind=engine)

View File

@@ -0,0 +1,11 @@
[project]
name = "todo-app"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = [
"fastapi",
"uvicorn[standard]",
"sqlalchemy",
"pytest",
"httpx",
]

View File

@@ -0,0 +1,63 @@
{
"run_id": "tmpl_v2",
"model": "qwen2.5-coder:7b-instruct-q4_K_M",
"description": "Todo-sovellus FastAPI + SQLite, CRUD-endpointit ja testit",
"spec": {
"project_name": "todo-app",
"description": "A simple Todo application with CRUD endpoints using FastAPI and SQLite.",
"entities": [
{
"name": "Todo",
"table_name": "todos",
"fields": [
{
"name": "title",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "description",
"sa_type": "Text",
"py_type": "str | None",
"nullable": true,
"default": null
},
{
"name": "due_date",
"sa_type": "Date",
"py_type": "date | None",
"nullable": true,
"default": null
},
{
"name": "status",
"sa_type": "String(20)",
"py_type": "str",
"nullable": false,
"default": "pending"
}
]
}
],
"extra_imports": [
"from datetime import date"
]
},
"files": {
"models.py": 712,
"schemas.py": 293,
"main.py": 1711,
"test_main.py": 2394,
"pyproject.toml": 177,
"Dockerfile": 339
},
"valid": true,
"docker": {
"build": true,
"pytest": true,
"api": true,
"errors": []
}
}

View File

@@ -0,0 +1,14 @@
from pydantic import BaseModel
from datetime import date
class TodoCreate(BaseModel):
title: str
description: str | None = None
due_date: date | None = None
status: str = "pending"
class TodoResponse(TodoCreate):
id: int
class Config:
from_attributes = True

View File

@@ -0,0 +1,43 @@
{
"project_name": "todo-app",
"description": "A simple Todo application with CRUD endpoints using FastAPI and SQLite.",
"entities": [
{
"name": "Todo",
"table_name": "todos",
"fields": [
{
"name": "title",
"sa_type": "String(255)",
"py_type": "str",
"nullable": false,
"default": null
},
{
"name": "description",
"sa_type": "Text",
"py_type": "str | None",
"nullable": true,
"default": null
},
{
"name": "due_date",
"sa_type": "Date",
"py_type": "date | None",
"nullable": true,
"default": null
},
{
"name": "status",
"sa_type": "String(20)",
"py_type": "str",
"nullable": false,
"default": "pending"
}
]
}
],
"extra_imports": [
"from datetime import date"
]
}

View File

@@ -0,0 +1,58 @@
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app, get_db
from models import Base
TEST_DB = "sqlite:///./test.db"
test_engine = create_engine(TEST_DB, connect_args={"check_same_thread": False})
TestSession = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)
Base.metadata.create_all(bind=test_engine)
def override_get_db():
db = TestSession()
try:
yield db
finally:
db.close()
app.dependency_overrides[get_db] = override_get_db
client = TestClient(app)
def test_create_todo():
response = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
assert response.status_code == 201
data = response.json()
assert "id" in data
def test_list_todos():
client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
response = client.get('/todos/')
assert response.status_code == 200
assert len(response.json()) >= 1
def test_get_todo_by_id():
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
item_id = created['id']
response = client.get(f'/todos/{item_id}')
assert response.status_code == 200
assert response.json()['id'] == item_id
def test_get_todo_not_found():
response = client.get('/todos/99999')
assert response.status_code == 404
def test_update_todo():
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
item_id = created['id']
response = client.put(f'/todos/{item_id}', json={"title": "Updated title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"})
assert response.status_code == 200
def test_delete_todo():
created = client.post('/todos/', json={"title": "Test title", "description": "Test description", "due_date": "2024-01-15", "status": "pending"}).json()
item_id = created['id']
response = client.delete(f'/todos/{item_id}')
assert response.status_code == 204
response = client.get(f'/todos/{item_id}')
assert response.status_code == 404