mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
Merge pull request #211 from grillazz/12-add-json-field-example
12-add-json-field-example
This commit is contained in:
commit
5630196739
2
Makefile
2
Makefile
@ -21,7 +21,7 @@ docker-apply-db-migrations: ## apply alembic migrations to database/schema
|
|||||||
docker compose run --rm app alembic upgrade head
|
docker compose run --rm app alembic upgrade head
|
||||||
|
|
||||||
.PHONY: docker-create-db-migration
|
.PHONY: docker-create-db-migration
|
||||||
docker-create-db-migration: ## Create new alembic database migration aka database revision.
|
docker-create-db-migration: ## Create new alembic database migration aka database revision. Example: make docker-create-db-migration msg="add users table"
|
||||||
docker compose up -d db | true
|
docker compose up -d db | true
|
||||||
docker compose run --no-deps app alembic revision --autogenerate -m "$(msg)"
|
docker compose run --no-deps app alembic revision --autogenerate -m "$(msg)"
|
||||||
|
|
||||||
|
@ -0,0 +1,37 @@
|
|||||||
|
"""add json chaos
|
||||||
|
|
||||||
|
Revision ID: d021bd4763a5
|
||||||
|
Revises: 0c69050b5a3e
|
||||||
|
Create Date: 2025-07-29 15:21:19.415583
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'd021bd4763a5'
|
||||||
|
down_revision = '0c69050b5a3e'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('random_stuff',
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('chaos', postgresql.JSON(astext_type=sa.Text()), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
schema='happy_hog'
|
||||||
|
)
|
||||||
|
op.create_unique_constraint(None, 'nonsense', ['name'], schema='happy_hog')
|
||||||
|
op.create_unique_constraint(None, 'stuff', ['name'], schema='happy_hog')
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_constraint(None, 'stuff', schema='happy_hog', type_='unique')
|
||||||
|
op.drop_constraint(None, 'nonsense', schema='happy_hog', type_='unique')
|
||||||
|
op.drop_table('random_stuff', schema='happy_hog')
|
||||||
|
# ### end Alembic commands ###
|
@ -4,7 +4,8 @@ from sqlalchemy.exc import SQLAlchemyError
|
|||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
from app.database import get_db
|
from app.database import get_db
|
||||||
from app.models.stuff import Stuff
|
from app.models.stuff import RandomStuff, Stuff
|
||||||
|
from app.schemas.stuff import RandomStuff as RandomStuffSchema
|
||||||
from app.schemas.stuff import StuffResponse, StuffSchema
|
from app.schemas.stuff import StuffResponse, StuffSchema
|
||||||
|
|
||||||
logger = AppStructLogger().get_logger()
|
logger = AppStructLogger().get_logger()
|
||||||
@ -12,6 +13,15 @@ logger = AppStructLogger().get_logger()
|
|||||||
router = APIRouter(prefix="/v1/stuff")
|
router = APIRouter(prefix="/v1/stuff")
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/random", status_code=status.HTTP_201_CREATED)
|
||||||
|
async def create_random_stuff(
|
||||||
|
payload: RandomStuffSchema, db_session: AsyncSession = Depends(get_db)
|
||||||
|
) -> dict[str, str]:
|
||||||
|
random_stuff = RandomStuff(**payload.model_dump())
|
||||||
|
await random_stuff.save(db_session)
|
||||||
|
return {"id": str(random_stuff.id)}
|
||||||
|
|
||||||
|
|
||||||
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
|
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
|
||||||
async def create_multi_stuff(
|
async def create_multi_stuff(
|
||||||
payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)
|
payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)
|
||||||
|
11
app/main.py
11
app/main.py
@ -20,6 +20,7 @@ from app.services.auth import AuthBearer
|
|||||||
logger = AppStructLogger().get_logger()
|
logger = AppStructLogger().get_logger()
|
||||||
templates = Jinja2Templates(directory=Path(__file__).parent.parent / "templates")
|
templates = Jinja2Templates(directory=Path(__file__).parent.parent / "templates")
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
app.redis = await get_redis()
|
app.redis = await get_redis()
|
||||||
@ -30,12 +31,15 @@ async def lifespan(app: FastAPI):
|
|||||||
min_size=5,
|
min_size=5,
|
||||||
max_size=20,
|
max_size=20,
|
||||||
)
|
)
|
||||||
await logger.ainfo("Postgres pool created", idle_size=app.postgres_pool.get_idle_size())
|
await logger.ainfo(
|
||||||
|
"Postgres pool created", idle_size=app.postgres_pool.get_idle_size()
|
||||||
|
)
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
await app.redis.close()
|
await app.redis.close()
|
||||||
await app.postgres_pool.close()
|
await app.postgres_pool.close()
|
||||||
|
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
def create_app() -> FastAPI:
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="Stuff And Nonsense API",
|
title="Stuff And Nonsense API",
|
||||||
@ -47,7 +51,9 @@ def create_app() -> FastAPI:
|
|||||||
app.include_router(shakespeare_router)
|
app.include_router(shakespeare_router)
|
||||||
app.include_router(user_router)
|
app.include_router(user_router)
|
||||||
app.include_router(ml_router, prefix="/v1/ml", tags=["ML"])
|
app.include_router(ml_router, prefix="/v1/ml", tags=["ML"])
|
||||||
app.include_router(health_router, prefix="/v1/public/health", tags=["Health, Public"])
|
app.include_router(
|
||||||
|
health_router, prefix="/v1/public/health", tags=["Health, Public"]
|
||||||
|
)
|
||||||
app.include_router(
|
app.include_router(
|
||||||
health_router,
|
health_router,
|
||||||
prefix="/v1/health",
|
prefix="/v1/health",
|
||||||
@ -61,6 +67,7 @@ def create_app() -> FastAPI:
|
|||||||
|
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|
||||||
app = create_app()
|
app = create_app()
|
||||||
|
|
||||||
# --- Unused/experimental code and TODOs ---
|
# --- Unused/experimental code and TODOs ---
|
||||||
|
@ -27,7 +27,9 @@ class Base(DeclarativeBase):
|
|||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
db_session.add(self)
|
db_session.add(self)
|
||||||
return await db_session.commit()
|
await db_session.commit()
|
||||||
|
await db_session.refresh(self)
|
||||||
|
return self
|
||||||
except SQLAlchemyError as ex:
|
except SQLAlchemyError as ex:
|
||||||
await logger.aerror(f"Error inserting instance of {self}: {repr(ex)}")
|
await logger.aerror(f"Error inserting instance of {self}: {repr(ex)}")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
from sqlalchemy import ForeignKey, String, select
|
from sqlalchemy import ForeignKey, String, select
|
||||||
from sqlalchemy.dialects.postgresql import UUID
|
from sqlalchemy.dialects.postgresql import JSON, UUID
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from sqlalchemy.orm import Mapped, joinedload, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, joinedload, mapped_column, relationship
|
||||||
|
|
||||||
@ -10,6 +10,16 @@ from app.models.nonsense import Nonsense
|
|||||||
from app.utils.decorators import compile_sql_or_scalar
|
from app.utils.decorators import compile_sql_or_scalar
|
||||||
|
|
||||||
|
|
||||||
|
class RandomStuff(Base):
|
||||||
|
__tablename__ = "random_stuff"
|
||||||
|
__table_args__ = ({"schema": "happy_hog"},)
|
||||||
|
|
||||||
|
id: Mapped[uuid.UUID] = mapped_column(
|
||||||
|
UUID(as_uuid=True), default=uuid.uuid4, primary_key=True
|
||||||
|
)
|
||||||
|
chaos: Mapped[dict] = mapped_column(JSON)
|
||||||
|
|
||||||
|
|
||||||
class Stuff(Base):
|
class Stuff(Base):
|
||||||
__tablename__ = "stuff"
|
__tablename__ = "stuff"
|
||||||
__table_args__ = ({"schema": "happy_hog"},)
|
__table_args__ = ({"schema": "happy_hog"},)
|
||||||
|
@ -1,3 +1,4 @@
|
|||||||
|
from typing import Any
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from pydantic import BaseModel, ConfigDict, Field
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
@ -5,6 +6,10 @@ from pydantic import BaseModel, ConfigDict, Field
|
|||||||
config = ConfigDict(from_attributes=True)
|
config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
|
||||||
|
class RandomStuff(BaseModel):
|
||||||
|
chaos: dict[str, Any] = Field(..., description="JSON data for chaos field")
|
||||||
|
|
||||||
|
|
||||||
class StuffSchema(BaseModel):
|
class StuffSchema(BaseModel):
|
||||||
name: str = Field(
|
name: str = Field(
|
||||||
title="",
|
title="",
|
||||||
|
@ -30,7 +30,7 @@ class RotatingBytesLogger:
|
|||||||
lineno=0,
|
lineno=0,
|
||||||
msg=message.rstrip("\n"),
|
msg=message.rstrip("\n"),
|
||||||
args=(),
|
args=(),
|
||||||
exc_info=None
|
exc_info=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Check if rotation is needed before emitting
|
# Check if rotation is needed before emitting
|
||||||
@ -78,7 +78,7 @@ class AppStructLogger(metaclass=SingletonMetaNoArgs):
|
|||||||
filename=_log_path,
|
filename=_log_path,
|
||||||
maxBytes=10 * 1024 * 1024, # 10MB
|
maxBytes=10 * 1024 * 1024, # 10MB
|
||||||
backupCount=5,
|
backupCount=5,
|
||||||
encoding="utf-8"
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
structlog.configure(
|
structlog.configure(
|
||||||
cache_logger_on_first_use=True,
|
cache_logger_on_first_use=True,
|
||||||
@ -90,7 +90,7 @@ class AppStructLogger(metaclass=SingletonMetaNoArgs):
|
|||||||
structlog.processors.TimeStamper(fmt="iso", utc=True),
|
structlog.processors.TimeStamper(fmt="iso", utc=True),
|
||||||
structlog.processors.JSONRenderer(serializer=orjson.dumps),
|
structlog.processors.JSONRenderer(serializer=orjson.dumps),
|
||||||
],
|
],
|
||||||
logger_factory=RotatingBytesLoggerFactory(_handler)
|
logger_factory=RotatingBytesLoggerFactory(_handler),
|
||||||
)
|
)
|
||||||
self._logger = structlog.get_logger()
|
self._logger = structlog.get_logger()
|
||||||
|
|
||||||
|
@ -18,6 +18,7 @@ services:
|
|||||||
- ./app:/panettone/app
|
- ./app:/panettone/app
|
||||||
- ./tests:/panettone/tests
|
- ./tests:/panettone/tests
|
||||||
- ./templates:/panettone/templates
|
- ./templates:/panettone/templates
|
||||||
|
- ./alembic:/panettone/alembic
|
||||||
ports:
|
ports:
|
||||||
- "8080:8080"
|
- "8080:8080"
|
||||||
depends_on:
|
depends_on:
|
||||||
|
Loading…
x
Reference in New Issue
Block a user