init codebase

This commit is contained in:
grillazz
2021-03-26 11:07:52 +01:00
parent 5e9e294b27
commit d7e0db47e5
21 changed files with 367 additions and 1 deletions

View File

23
the_app/models/base.py Normal file
View File

@@ -0,0 +1,23 @@
from typing import Any
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
id: Any
__name__: str
# Generate __tablename__ automatically
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
async def save(self, db_session: AsyncSession):
try:
db_session.add(self)
return await db_session.commit()
except SQLAlchemyError as ex:
print(f"Have to rollback, save failed: {ex}")
raise

46
the_app/models/stuff.py Normal file
View File

@@ -0,0 +1,46 @@
import uuid
from sqlalchemy import Column, String, delete, select
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from the_app.models.base import Base
from the_app.schemas.stuff import StuffSchema
class Stuff(Base):
__tablename__ = "stuff"
id = Column(UUID(as_uuid=True), unique=True, default=uuid.uuid4, autoincrement=True)
name = Column(String, nullable=False, primary_key=True, unique=True)
description = Column(String, nullable=False, unique=True)
def __init__(self, name: str, description: str):
self.name = name
self.description = description
@classmethod
async def create(cls, db_session: AsyncSession, schema: StuffSchema):
stuff = Stuff(
name=schema.name,
description=schema.description,
)
await stuff.save(db_session)
return stuff.id
async def update(self, db_session: AsyncSession, schema: StuffSchema):
self.name = schema.name
self.description = schema.description
return await self.save(db_session)
@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