Skip to content

Commit d722504

Browse files
committed
wip: crud refactor
1 parent 93f2e66 commit d722504

File tree

6 files changed

+30
-31
lines changed

6 files changed

+30
-31
lines changed

app/api/stuff.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,5 +116,5 @@ async def update_stuff(
116116
db_session: AsyncSession = Depends(get_db),
117117
):
118118
stuff = await Stuff.find(db_session, name)
119-
await stuff.update(db_session, **payload.model_dump())
119+
await stuff.update(**payload.model_dump())
120120
return stuff

app/database.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ async def get_db() -> AsyncGenerator:
2828
# logger.debug(f"ASYNC Pool: {engine.pool.status()}")
2929
try:
3030
yield session
31+
await session.commit()
3132
except Exception as e:
3233
await logger.aerror(f"Error getting database session: {e}")
3334
raise

app/main.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33

44
import asyncpg
55
from fastapi import Depends, FastAPI, Request
6-
from fastapi.responses import HTMLResponse
6+
from fastapi.responses import HTMLResponse, JSONResponse
77
from fastapi.templating import Jinja2Templates
88
from rotoger import AppStructLogger
9+
from sqlalchemy.exc import SQLAlchemyError
910

1011
from app.api.health import router as health_router
1112
from app.api.ml import router as ml_router
@@ -61,6 +62,19 @@ def create_app() -> FastAPI:
6162
dependencies=[Depends(AuthBearer())],
6263
)
6364

65+
@app.exception_handler(SQLAlchemyError)
66+
async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
67+
await logger.aerror(
68+
"A database error occurred",
69+
sql_error=repr(exc),
70+
request_url=request.url.path,
71+
request_body=request.body,
72+
)
73+
return JSONResponse(
74+
status_code=500,
75+
content={"message": "A database error occurred. Please try again later."},
76+
)
77+
6478
@app.get("/index", response_class=HTMLResponse)
6579
def get_index(request: Request):
6680
return templates.TemplateResponse("index.html", {"request": request})

app/models/base.py

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -20,64 +20,46 @@ def __tablename__(self) -> str:
2020
return self.__name__.lower()
2121

2222
async def save(self, db_session: AsyncSession):
23-
"""
24-
25-
:param db_session:
26-
:return:
27-
"""
2823
try:
2924
db_session.add(self)
30-
await db_session.commit()
25+
await db_session.flush()
3126
await db_session.refresh(self)
3227
return self
3328
except SQLAlchemyError as ex:
3429
await logger.aerror(f"Error inserting instance of {self}: {repr(ex)}")
35-
raise HTTPException(
36-
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
37-
) from ex
30+
raise # This will make the exception handler catch it
3831

3932
async def delete(self, db_session: AsyncSession):
40-
"""
41-
42-
:param db_session:
43-
:return:
44-
"""
4533
try:
4634
await db_session.delete(self)
47-
await db_session.commit()
4835
return True
4936
except SQLAlchemyError as ex:
5037
raise HTTPException(
5138
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
5239
) from ex
5340

54-
async def update(self, db: AsyncSession, **kwargs):
55-
"""
56-
57-
:param db:
58-
:param kwargs
59-
:return:
60-
"""
41+
async def update(self, **kwargs):
6142
try:
6243
for k, v in kwargs.items():
6344
setattr(self, k, v)
64-
return await db.commit()
45+
return True
6546
except SQLAlchemyError as ex:
6647
raise HTTPException(
6748
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)
6849
) from ex
6950

70-
async def save_or_update(self, db: AsyncSession):
51+
async def save_or_update(self, db_session: AsyncSession):
7152
try:
72-
db.add(self)
73-
return await db.commit()
53+
db_session.add(self)
54+
await db_session.flush()
55+
return True
7456
except IntegrityError as exception:
7557
if isinstance(exception.orig, UniqueViolationError):
76-
return await db.merge(self)
58+
return await db_session.merge(self)
7759
else:
7860
raise HTTPException(
7961
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
8062
detail=repr(exception),
8163
) from exception
8264
finally:
83-
await db.close()
65+
await db_session.close()

app/schemas/stuff.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,9 @@
77

88

99
class RandomStuff(BaseModel):
10-
chaos: dict[str, Any] = Field(..., description="JSON data for chaos field")
10+
chaos: dict[str, Any] = Field(
11+
..., description="Pretty chaotic JSON data can be added here..."
12+
)
1113

1214

1315
class StuffSchema(BaseModel):

tests/api/test_chaotic_stuff.py

Whitespace-only changes.

0 commit comments

Comments
 (0)