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