mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-11-30 13:20:40 +03:00
move delete method to base class, minor api updates and code linting
This commit is contained in:
@@ -1,10 +1,10 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from icecream import ic
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.ext.declarative import as_declarative, declared_attr
|
||||
from fastapi import HTTPException, status
|
||||
from icecream import ic
|
||||
|
||||
|
||||
@as_declarative()
|
||||
@@ -24,3 +24,13 @@ class Base:
|
||||
ic("Have to rollback, save failed:")
|
||||
ic(ex)
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=ex.__str__())
|
||||
|
||||
async def delete(self, db_session: AsyncSession):
|
||||
try:
|
||||
await db_session.delete(self)
|
||||
await db_session.commit()
|
||||
return True
|
||||
except SQLAlchemyError as ex:
|
||||
ic("Have to rollback, save failed:")
|
||||
ic(ex)
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=ex.__str__())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import Column, String, delete, select
|
||||
from sqlalchemy import Column, String, select
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
@@ -25,22 +25,16 @@ class Stuff(Base):
|
||||
description=schema.description,
|
||||
)
|
||||
await stuff.save(db_session)
|
||||
return stuff.id
|
||||
return stuff
|
||||
|
||||
async def update(self, db_session: AsyncSession, schema: StuffSchema):
|
||||
self.name = schema.name
|
||||
self.description = schema.description
|
||||
return await self.save(db_session)
|
||||
await self.save(db_session)
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
async def find(cls, db_session: AsyncSession, name: str):
|
||||
stmt = select(cls).where(cls.name == name)
|
||||
result = await db_session.execute(stmt)
|
||||
return result.scalars().first()
|
||||
|
||||
@classmethod
|
||||
async def delete(cls, db_session: AsyncSession, stuff_id: UUID):
|
||||
stmt = delete(cls).where(cls.id == stuff_id)
|
||||
await db_session.execute(stmt)
|
||||
await db_session.commit()
|
||||
return True
|
||||
|
||||
Reference in New Issue
Block a user