这边使用的是flask+dependency-injecter+sqlalchemy,有一个公共类,想插入或者更新的时候对公共类某些字段进行统一操作
这个是公共类:包括一些基础字段,所有的实体都会继承这个类
"""Models module."""
from datetime import datetime
from sqlalchemy import Column, String, Integer,DateTime#, Boolean
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class CommonEntity(Base):
__abstract__ = True
created_dt = Column(DateTime)
created_by = Column(String)
updated_dt = Column(DateTime)
updated_by = Column(String)
version = Column(Integer)
然后是db的配置文章来源:https://www.toymoban.com/news/detail-786393.html
"""Database module."""
from contextlib import contextmanager, AbstractContextManager
from typing import Callable
from sqlalchemy import create_engine, orm,event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from datetime import datetime
from main.services.common_service.db_access.domain.common_field_entity import CommonEntity
Base = declarative_base()
class DatabaseConfig:
def __init__(self, db_url: str) -> None:
self._engine = create_engine(db_url, echo=True)
self._session_factory = orm.scoped_session(
orm.sessionmaker(
autocommit=False,
autoflush=False,
expire_on_commit=False,
bind=self._engine,
),
)
def create_database(self) -> None:
Base.metadata.create_all(self._engine)
@contextmanager
def session(self) -> Callable[..., AbstractContextManager[Session]]:
session: Session = self._session_factory()
try:
yield session
except Exception:
session.rollback()
raise
else:
if session._transaction.is_active:
session.commit()
session.close()
@event.listens_for(CommonEntity, 'before_insert', propagate=True)
def before_insert_listener(self, mapper, target):
# 在创建时自动更新 created_dt,version
target.created_dt = datetime.now()
target.created_by = 'Damien'
target.version = 1
@event.listens_for(CommonEntity, 'before_update', propagate=True)
def before_update_listener(self, mapper, target):
# 在更新时自动更新 updated_dt,version
target.updated_dt = datetime.now()
target.updated_by = 'Damien'
target.version += 1
重要的就是@event.listens_for,这里。监听公共类,所有继承了它的实体的插入更新都会被监听到,然后就是对里面的字段进行统一的操作就行了,不用再每次插入或者更新进行手动修改了文章来源地址https://www.toymoban.com/news/detail-786393.html
到了这里,关于sqlalchemy 监听所有实体插入以及更新事件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!