Skip to content

Commit 5630196

Browse files
authored
Merge pull request #211 from grillazz/12-add-json-field-example
12-add-json-field-example
2 parents 72bb711 + 93f2e66 commit 5630196

File tree

9 files changed

+81
-9
lines changed

9 files changed

+81
-9
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ docker-apply-db-migrations: ## apply alembic migrations to database/schema
2121
docker compose run --rm app alembic upgrade head
2222

2323
.PHONY: docker-create-db-migration
24-
docker-create-db-migration: ## Create new alembic database migration aka database revision.
24+
docker-create-db-migration: ## Create new alembic database migration aka database revision. Example: make docker-create-db-migration msg="add users table"
2525
docker compose up -d db | true
2626
docker compose run --no-deps app alembic revision --autogenerate -m "$(msg)"
2727

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""add json chaos
2+
3+
Revision ID: d021bd4763a5
4+
Revises: 0c69050b5a3e
5+
Create Date: 2025-07-29 15:21:19.415583
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
from sqlalchemy.dialects import postgresql
11+
12+
# revision identifiers, used by Alembic.
13+
revision = 'd021bd4763a5'
14+
down_revision = '0c69050b5a3e'
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table('random_stuff',
22+
sa.Column('id', sa.UUID(), nullable=False),
23+
sa.Column('chaos', postgresql.JSON(astext_type=sa.Text()), nullable=False),
24+
sa.PrimaryKeyConstraint('id'),
25+
schema='happy_hog'
26+
)
27+
op.create_unique_constraint(None, 'nonsense', ['name'], schema='happy_hog')
28+
op.create_unique_constraint(None, 'stuff', ['name'], schema='happy_hog')
29+
# ### end Alembic commands ###
30+
31+
32+
def downgrade():
33+
# ### commands auto generated by Alembic - please adjust! ###
34+
op.drop_constraint(None, 'stuff', schema='happy_hog', type_='unique')
35+
op.drop_constraint(None, 'nonsense', schema='happy_hog', type_='unique')
36+
op.drop_table('random_stuff', schema='happy_hog')
37+
# ### end Alembic commands ###

app/api/stuff.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,24 @@
44
from sqlalchemy.ext.asyncio import AsyncSession
55

66
from app.database import get_db
7-
from app.models.stuff import Stuff
7+
from app.models.stuff import RandomStuff, Stuff
8+
from app.schemas.stuff import RandomStuff as RandomStuffSchema
89
from app.schemas.stuff import StuffResponse, StuffSchema
910

1011
logger = AppStructLogger().get_logger()
1112

1213
router = APIRouter(prefix="/v1/stuff")
1314

1415

16+
@router.post("/random", status_code=status.HTTP_201_CREATED)
17+
async def create_random_stuff(
18+
payload: RandomStuffSchema, db_session: AsyncSession = Depends(get_db)
19+
) -> dict[str, str]:
20+
random_stuff = RandomStuff(**payload.model_dump())
21+
await random_stuff.save(db_session)
22+
return {"id": str(random_stuff.id)}
23+
24+
1525
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
1626
async def create_multi_stuff(
1727
payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)

app/main.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
logger = AppStructLogger().get_logger()
2121
templates = Jinja2Templates(directory=Path(__file__).parent.parent / "templates")
2222

23+
2324
@asynccontextmanager
2425
async def lifespan(app: FastAPI):
2526
app.redis = await get_redis()
@@ -30,12 +31,15 @@ async def lifespan(app: FastAPI):
3031
min_size=5,
3132
max_size=20,
3233
)
33-
await logger.ainfo("Postgres pool created", idle_size=app.postgres_pool.get_idle_size())
34+
await logger.ainfo(
35+
"Postgres pool created", idle_size=app.postgres_pool.get_idle_size()
36+
)
3437
yield
3538
finally:
3639
await app.redis.close()
3740
await app.postgres_pool.close()
3841

42+
3943
def create_app() -> FastAPI:
4044
app = FastAPI(
4145
title="Stuff And Nonsense API",
@@ -47,7 +51,9 @@ def create_app() -> FastAPI:
4751
app.include_router(shakespeare_router)
4852
app.include_router(user_router)
4953
app.include_router(ml_router, prefix="/v1/ml", tags=["ML"])
50-
app.include_router(health_router, prefix="/v1/public/health", tags=["Health, Public"])
54+
app.include_router(
55+
health_router, prefix="/v1/public/health", tags=["Health, Public"]
56+
)
5157
app.include_router(
5258
health_router,
5359
prefix="/v1/health",
@@ -61,6 +67,7 @@ def get_index(request: Request):
6167

6268
return app
6369

70+
6471
app = create_app()
6572

6673
# --- Unused/experimental code and TODOs ---

app/models/base.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ async def save(self, db_session: AsyncSession):
2727
"""
2828
try:
2929
db_session.add(self)
30-
return await db_session.commit()
30+
await db_session.commit()
31+
await db_session.refresh(self)
32+
return self
3133
except SQLAlchemyError as ex:
3234
await logger.aerror(f"Error inserting instance of {self}: {repr(ex)}")
3335
raise HTTPException(

app/models/stuff.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import uuid
22

33
from sqlalchemy import ForeignKey, String, select
4-
from sqlalchemy.dialects.postgresql import UUID
4+
from sqlalchemy.dialects.postgresql import JSON, UUID
55
from sqlalchemy.ext.asyncio import AsyncSession
66
from sqlalchemy.orm import Mapped, joinedload, mapped_column, relationship
77

@@ -10,6 +10,16 @@
1010
from app.utils.decorators import compile_sql_or_scalar
1111

1212

13+
class RandomStuff(Base):
14+
__tablename__ = "random_stuff"
15+
__table_args__ = ({"schema": "happy_hog"},)
16+
17+
id: Mapped[uuid.UUID] = mapped_column(
18+
UUID(as_uuid=True), default=uuid.uuid4, primary_key=True
19+
)
20+
chaos: Mapped[dict] = mapped_column(JSON)
21+
22+
1323
class Stuff(Base):
1424
__tablename__ = "stuff"
1525
__table_args__ = ({"schema": "happy_hog"},)

app/schemas/stuff.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
1+
from typing import Any
12
from uuid import UUID
23

34
from pydantic import BaseModel, ConfigDict, Field
45

56
config = ConfigDict(from_attributes=True)
67

78

9+
class RandomStuff(BaseModel):
10+
chaos: dict[str, Any] = Field(..., description="JSON data for chaos field")
11+
12+
813
class StuffSchema(BaseModel):
914
name: str = Field(
1015
title="",

app/utils/logging.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def msg(self, message):
3030
lineno=0,
3131
msg=message.rstrip("\n"),
3232
args=(),
33-
exc_info=None
33+
exc_info=None,
3434
)
3535

3636
# Check if rotation is needed before emitting
@@ -78,7 +78,7 @@ def __attrs_post_init__(self):
7878
filename=_log_path,
7979
maxBytes=10 * 1024 * 1024, # 10MB
8080
backupCount=5,
81-
encoding="utf-8"
81+
encoding="utf-8",
8282
)
8383
structlog.configure(
8484
cache_logger_on_first_use=True,
@@ -90,7 +90,7 @@ def __attrs_post_init__(self):
9090
structlog.processors.TimeStamper(fmt="iso", utc=True),
9191
structlog.processors.JSONRenderer(serializer=orjson.dumps),
9292
],
93-
logger_factory=RotatingBytesLoggerFactory(_handler)
93+
logger_factory=RotatingBytesLoggerFactory(_handler),
9494
)
9595
self._logger = structlog.get_logger()
9696

compose.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ services:
1818
- ./app:/panettone/app
1919
- ./tests:/panettone/tests
2020
- ./templates:/panettone/templates
21+
- ./alembic:/panettone/alembic
2122
ports:
2223
- "8080:8080"
2324
depends_on:

0 commit comments

Comments
 (0)