我正在同时尝试2种新事物,因此在简化和阐明方面均提供了帮助。
from sqlalchemy.ext.declarative import declared_attr from sqlalchemy import Column, Float, event class TimeStampMixin(object): @declared_attr def __tablename__(cls): return cls.__name__.lower() created = Column(Float) modified = Column(Float) def __init__(self, created = None, modified = None): self.created = created self.modified = modified def create_time(mapper, connection, target): target.created = time() #def modified_time(mapper, connection, target): # target.modified = time() event.listen(TimeStampMixin, 'before_insert', create_time) #event.listen(TimeStampMixin, 'before_update', modified_time)
所以我想创建一个mixin,可以在任何课程中应用:
class MyClass(TimeStampMixin, Base): etc, etc, etc
此类继承了在创建时创建时间戳并在更新时创建/修改时间戳的功能。
导入时出现此错误:
raise exc.UnmappedClassError(class_) sqlalchemy.orm.exc.UnmappedClassError: Class 'db.database.TimeStampMixin' is not mapped
在这一点上,我很沮丧。
这是我要侦听before_insert事件的方法:classmethod在您的TimeStampMixin上注册当前类并处理设置创建时间。
before_insert
classmethod
TimeStampMixin
例如
class TimeStampMixin(object): # other class methods @staticmethod def create_time(mapper, connection, target): target.created = time() @classmethod def register(cls): sqlalchemy.event.listen(cls, 'before_insert', cls.create_time)
这样,您可以:
您可以简单地使用它:
class MyMappedClass(TimeStampMixin, Base): pass MyMappedClass.register()
简单,非常清晰,没有魔力,但仍然可以根据您的需要进行封装。