253 lines
9.0 KiB
Markdown
253 lines
9.0 KiB
Markdown
# 3 — Coder (coder) — main.py
|
|
|
|
**Malli:** `qwen-coder`
|
|
|
|
## System Prompt
|
|
|
|
```
|
|
You are an expert Python developer. Write complete, production-ready code.
|
|
|
|
CRITICAL RULES:
|
|
1. Include ALL imports at the top of every file — including stdlib (from datetime import date, etc.)
|
|
2. Import from other project files: from models import Todo, SessionLocal
|
|
3. NEVER use relative imports (from .models) — ALWAYS absolute: from models import ...
|
|
4. Pydantic schemas use different names than SQLAlchemy models: TodoCreate, TodoResponse (not Todo)
|
|
5. SQLAlchemy engine: create_engine(url, connect_args={"check_same_thread": False})
|
|
6. SessionLocal: sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
7. FastAPI dependencies: def get_db(): db = SessionLocal(); try: yield db; finally: db.close()
|
|
8. Pydantic v2: use model_dump() not dict(), class Config: from_attributes = True
|
|
9. All CRUD endpoints: POST (201), GET list, GET by id, PUT, DELETE (204)
|
|
|
|
NEVER:
|
|
- Leave out any import (EVERY type you use must be imported)
|
|
- Use relative imports (from .models)
|
|
- Add explanations or comments
|
|
- Leave placeholder code or TODO comments
|
|
- Use Flask syntax (app.run) in FastAPI projects
|
|
- Use requirements.txt or Poetry — always use pyproject.toml with [project] format (PEP 621)
|
|
- Use pip install — use uv (e.g. uv run uvicorn main:app --reload)
|
|
```
|
|
|
|
## Syöte
|
|
|
|
```
|
|
You are an expert Python developer. Write complete, production-ready code.
|
|
|
|
CRITICAL RULES:
|
|
1. Include ALL imports at the top of every file — including stdlib (from datetime import date, etc.)
|
|
2. Import from other project files: from models import Todo, SessionLocal
|
|
3. NEVER use relative imports (from .models) — ALWAYS absolute: from models import ...
|
|
4. Pydantic schemas use different names than SQLAlchemy models: TodoCreate, TodoResponse (not Todo)
|
|
5. SQLAlchemy engine: create_engine(url, connect_args={"check_same_thread": False})
|
|
6. SessionLocal: sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
7. FastAPI dependencies: def get_db(): db = SessionLocal(); try: yield db; finally: db.close()
|
|
8. Pydantic v2: use model_dump() not dict(), class Config: from_attributes = True
|
|
9. All CRUD endpoints: POST (201), GET list, GET by id, PUT, DELETE (204)
|
|
|
|
NEVER:
|
|
- Leave out any import (EVERY type you use must be imported)
|
|
- Use relative imports (from .models)
|
|
- Add explanations or comments
|
|
- Leave placeholder code or TODO comments
|
|
- Use Flask syntax (app.run) in FastAPI projects
|
|
- Use requirements.txt or Poetry — always use pyproject.toml with [project] format (PEP 621)
|
|
- Use pip install — use uv (e.g. uv run uvicorn main:app --reload)
|
|
|
|
EXAMPLE of main.py (for a different project, adapt to this one):
|
|
```
|
|
from fastapi import FastAPI, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from models import Base, engine, SessionLocal, Item
|
|
from schemas import ItemCreate, ItemResponse
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
app = FastAPI()
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
@app.post("/items/", response_model=ItemResponse, status_code=201)
|
|
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
|
|
db_item = Item(**item.model_dump())
|
|
db.add(db_item)
|
|
db.commit()
|
|
db.refresh(db_item)
|
|
return db_item
|
|
|
|
@app.get("/items/", response_model=list[ItemResponse])
|
|
def list_items(db: Session = Depends(get_db)):
|
|
return db.query(Item).all()
|
|
|
|
@app.get("/items/{item_id}", response_model=ItemResponse)
|
|
def get_item(item_id: int, db: Session = Depends(get_db)):
|
|
item = db.query(Item).filter(Item.id == item_id).first()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
return item
|
|
|
|
@app.put("/items/{item_id}", response_model=ItemResponse)
|
|
def update_item(item_id: int, item: ItemCreate, db: Session = Depends(get_db)):
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if not db_item:
|
|
raise HTTPException(status_code=404, detail="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("/items/{item_id}", status_code=204)
|
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
|
db_item = db.query(Item).filter(Item.id == item_id).first()
|
|
if not db_item:
|
|
raise HTTPException(status_code=404, detail="Not found")
|
|
db.delete(db_item)
|
|
db.commit()
|
|
```
|
|
|
|
Already written files in THIS project:
|
|
--- models.py ---
|
|
from sqlalchemy import create_engine, Column, Integer, String, DateTime, Text
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
from datetime import datetime
|
|
|
|
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(100), nullable=False)
|
|
description = Column(Text)
|
|
status = Column(String(20), default="pending")
|
|
created_at = Column(DateTime, default=datetime.utcnow)
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
--- schemas.py ---
|
|
from pydantic import BaseModel
|
|
|
|
class TaskCreate(BaseModel):
|
|
title: str
|
|
description: str | None = None
|
|
status: str = "pending"
|
|
|
|
class TaskResponse(TaskCreate):
|
|
id: int
|
|
|
|
class Config:
|
|
from_attributes = True
|
|
|
|
PROJECT REQUIREMENTS (from product owner):
|
|
### PROJECT NAME: Todo-App
|
|
|
|
### GOAL:
|
|
Create a simple task manager application for individuals to keep track of their daily tasks.
|
|
|
|
### CORE FEATURES:
|
|
1. **Add Task**: Users can add new tasks with title and description.
|
|
2. **View Tasks**: Users can see all their tasks in a list.
|
|
3. **Edit Task**: Users can update the details of an existing task.
|
|
4. **Delete Task**: Users can remove tasks they no longer need.
|
|
5. **Mark as Complete**: Users can mark tasks as completed.
|
|
6. **Filter Tasks**: Users can filter tasks by status (e.g., pending, completed).
|
|
7. **Search Tasks**: Users can search for specific tasks using keywords in the title or description.
|
|
|
|
### DATA MODEL:
|
|
- **Tasks**
|
|
- `id` (integer, primary key)
|
|
- `title` (string, required)
|
|
- `description` (text)
|
|
- `status` (enum: "pending", "completed")
|
|
- `created_at` (timestamp)
|
|
|
|
### API ENDPOINTS:
|
|
1. **GET /tasks**: Retrieve a list of all tasks.
|
|
2. **POST /tasks**: Create a new task with title, description, and status.
|
|
3. **PUT /tasks/{id}**: Update an existing task by ID.
|
|
4. **DELETE /tasks/{id}**: Delete a task by ID.
|
|
5. **GET /tasks/status/{status}**: Retrieve tasks filtered by status.
|
|
|
|
### CONSTRAINTS:
|
|
- Must use SQLite as the database.
|
|
- No authentication required for simplicity.
|
|
|
|
NOW write "main.py" for THIS project: Todo-sovellus FastAPI + SQLite, CRUD-endpointit ja testit
|
|
Create the FastAPI app with all CRUD endpoints:
|
|
- Import from models.py and schemas.py (use exact class names)
|
|
- create_all(bind=engine) at module level
|
|
- get_db dependency with yield pattern
|
|
- POST (201), GET list, GET by id, PUT, DELETE (204)
|
|
- Use response_model for type safety
|
|
- Use model_dump() not dict() (Pydantic v2)
|
|
Adapt to the project requirements. Import from already written files. Write ONLY the code, no explanations.
|
|
```
|
|
|
|
## Tulos
|
|
|
|
```
|
|
from fastapi import FastAPI, Depends, HTTPException, Query
|
|
from sqlalchemy.orm import Session
|
|
from models import Base, engine, SessionLocal, Task
|
|
from schemas import TaskCreate, TaskResponse
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
app = FastAPI()
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
@app.post("/tasks/", response_model=TaskResponse, status_code=201)
|
|
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])
|
|
def list_tasks(status: str | None = Query(None), db: Session = Depends(get_db)):
|
|
if status:
|
|
tasks = db.query(Task).filter(Task.status == status).all()
|
|
else:
|
|
tasks = db.query(Task).all()
|
|
return tasks
|
|
|
|
@app.get("/tasks/{task_id}", response_model=TaskResponse)
|
|
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="Not found")
|
|
return task
|
|
|
|
@app.put("/tasks/{task_id}", response_model=TaskResponse)
|
|
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="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)
|
|
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="Not found")
|
|
db.delete(db_task)
|
|
db.commit()
|
|
```
|