一旦你掌握了它的窍门,事件就非常简单。这是一个使用事件的快速示例
import uuid
from sqlalchemy.event import listen
from mypackage.models import Base
def generate_license(mapper, connect, target):
target.generate_license()
class User(Base):
__tablename__ = "users"
id = Column(String(36))
license = Column(String(256))
def generate_license(self):
if not self.license:
self.license = str(uuid.uuid4())
return self.license
listen(User, 'before_insert', generate_license)
或者,您可以使用装饰器:
from sqlalchemy.event import listens_for
…
class User(Base):
…
@listens_for(User, 'before_insert')
def generate_license(mapper, connect, self):
…