mirror of
https://github.com/grillazz/fastapi-sqlalchemy-asyncpg.git
synced 2025-08-26 16:40:40 +03:00
24 lines
637 B
Python
24 lines
637 B
Python
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
|