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,18 @@
```Dockerfile
FROM python:3.12-slim as builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
WORKDIR /app
COPY pyproject.toml .
RUN uv sync
COPY models.py schemas.py main.py test_main.py .
USER nonrootuser
EXPOSE 8000
CMD ["uv", "run", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
```

View File

@@ -0,0 +1,64 @@
from fastapi import FastAPI, HTTPException, Depends, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import date
from models import Task, engine
from schemas import TaskCreate, TaskResponse
app = FastAPI()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.post("/tasks/", response_model=TaskResponse, status_code=201)
async def create_task(task: TaskCreate, db: Session = Depends(get_db)):
db_task = Task(**task.model_dump())
db.add(db_task)
db.commit()
db.refresh(db_task)
return db_task
@app.get("/tasks/", response_model=List[TaskResponse])
async def get_tasks(status: Optional[str] = Query(None), db: Session = Depends(get_db)):
if status:
tasks = db.query(Task).filter_by(status=status).all()
else:
tasks = db.query(Task).all()
return tasks
@app.get("/tasks/{task_id}", response_model=TaskResponse)
async def get_task(task_id: int, db: Session = Depends(get_db)):
task = db.query(Task).filter(Task.id == task_id).first()
if not task:
raise HTTPException(status_code=404, detail="Task not found")
return task
@app.put("/tasks/{task_id}", response_model=TaskResponse)
async def update_task(task_id: int, task: TaskCreate, db: Session = Depends(get_db)):
db_task = db.query(Task).filter(Task.id == task_id).first()
if not db_task:
raise HTTPException(status_code=404, detail="Task not found")
for key, value in task.model_dump().items():
setattr(db_task, key, value)
db.commit()
db.refresh(db_task)
return db_task
@app.delete("/tasks/{task_id}", status_code=204)
async def delete_task(task_id: int, db: Session = Depends(get_db)):
db_task = db.query(Task).filter(Task.id == task_id).first()
if not db_task:
raise HTTPException(status_code=404, detail="Task not found")
db.delete(db_task)
db.commit()
return

View File

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

View File

@@ -0,0 +1,13 @@
[project]
name = "todo-app"
version = "0.1.0"
description = "A simple task management API using FastAPI and SQLAlchemy"
authors = [
{ name="Your Name", email="your.email@example.com" }
]
dependencies = [
"fastapi",
"uvicorn[standard]",
"sqlalchemy"
]

View File

@@ -0,0 +1,113 @@
{
"run_id": "v2_strict",
"steps": [
{
"step": "requirements",
"agent": "client",
"attempts": [
{
"attempt": 1,
"elapsed": 6.6,
"errors": [],
"code_length": 1190
}
],
"final_errors": [],
"passed": true
},
{
"step": "models.py",
"agent": "data",
"attempts": [
{
"attempt": 1,
"elapsed": 5.3,
"errors": [
"SQLite create_engine puuttuu connect_args={'check_same_thread': False}"
],
"code_length": 699
},
{
"attempt": 2,
"elapsed": 4.4,
"errors": [],
"code_length": 712
}
],
"final_errors": [],
"passed": true
},
{
"step": "schemas.py",
"agent": "coder",
"attempts": [
{
"attempt": 1,
"elapsed": 5.2,
"errors": [],
"code_length": 494
}
],
"final_errors": [],
"passed": true
},
{
"step": "main.py",
"agent": "coder",
"attempts": [
{
"attempt": 1,
"elapsed": 14.4,
"errors": [],
"code_length": 2036
}
],
"final_errors": [],
"passed": true
},
{
"step": "pyproject.toml",
"agent": "coder",
"attempts": [
{
"attempt": 1,
"elapsed": 3.3,
"errors": [],
"code_length": 267
}
],
"final_errors": [],
"passed": true
},
{
"step": "test_main.py",
"agent": "qa",
"attempts": [
{
"attempt": 1,
"elapsed": 16.4,
"errors": [],
"code_length": 2071
}
],
"final_errors": [],
"passed": true
},
{
"step": "Dockerfile",
"agent": "tester",
"attempts": [
{
"attempt": 1,
"elapsed": 3.5,
"errors": [],
"code_length": 314
}
],
"final_errors": [],
"passed": true
}
],
"model": "qwen2.5-coder:7b-instruct-q4_K_M",
"summary": "7/7 passed"
}

View File

@@ -0,0 +1,32 @@
**PROJECT NAME:** Todo-sovellus
**GOAL:** Create a simple task management application for individuals to keep track of their daily tasks and manage them efficiently.
**CORE FEATURES:**
1. Add new tasks with title, description, due date, and status.
2. View all tasks in a list format.
3. Filter tasks by status (e.g., pending, completed).
4. Update task details such as title, description, due date, and status.
5. Delete individual tasks.
6. Mark tasks as complete or incomplete.
7. Search for tasks by keywords in the title or description.
**DATA MODEL:**
1. **Task**
- id (integer, primary key)
- title (string, required)
- description (text, optional)
- due_date (date, optional)
- status (enum ['pending', 'completed'], default='pending')
**API ENDPOINTS:**
1. **GET /tasks** - Retrieve all tasks.
2. **POST /tasks** - Create a new task.
3. **GET /tasks/{id}** - Retrieve a specific task by ID.
4. **PUT /tasks/{id}** - Update an existing task.
5. **DELETE /tasks/{id}** - Delete a specific task.
6. **GET /tasks/status/{status}** - Filter tasks by status.
**CONSTRAINTS:**
- Must use SQLite as the database.
- No authentication is required for accessing endpoints.

View File

@@ -0,0 +1,18 @@
from pydantic import BaseModel, Field
from datetime import date
class TaskCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=255)
description: str | None = Field(None, max_length=255)
due_date: date | None = Field(None)
status: str = Field('pending', regex='^(pending|completed)$')
class TaskResponse(BaseModel):
id: int
title: str
description: str | None
due_date: date | None
status: str
class Config:
from_attributes = True

View File

@@ -0,0 +1,57 @@
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from main import app
from models import Base
engine = create_engine("sqlite:///:memory:", connect_args={"check_same_thread": False})
TestSession = sessionmaker(bind=engine)
Base.metadata.create_all(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 test_create_task():
response = client.post("/tasks/", json={"title": "Test Task", "description": "This is a test task"})
assert response.status_code == 201
assert response.json()["title"] == "Test Task"
assert response.json()["description"] == "This is a test task"
def test_get_tasks():
response = client.get("/tasks/")
assert response.status_code == 200
assert len(response.json()) > 0
def test_get_task_by_id():
response = client.post("/tasks/", json={"title": "Test Task", "description": "This is a test task"})
task_id = response.json()["id"]
response = client.get(f"/tasks/{task_id}")
assert response.status_code == 200
assert response.json()["id"] == task_id
def test_get_task_by_id_not_found():
response = client.get("/tasks/999")
assert response.status_code == 404
def test_update_task():
response = client.post("/tasks/", json={"title": "Test Task", "description": "This is a test task"})
task_id = response.json()["id"]
updated_data = {"title": "Updated Test Task"}
response = client.put(f"/tasks/{task_id}", json=updated_data)
assert response.status_code == 200
assert response.json()["title"] == "Updated Test Task"
def test_delete_task():
response = client.post("/tasks/", json={"title": "Test Task", "description": "This is a test task"})
task_id = response.json()["id"]
response = client.delete(f"/tasks/{task_id}")
assert response.status_code == 204
response = client.get(f"/tasks/{task_id}")
assert response.status_code == 404