13

我一次尝试 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

aaaand 我在这一点上被难住了。

4

4 回答 4

38

将您的侦听器附加到类方法中,它将事件附加到子类。

class TimeStampMixin(object):
    @staticmethod
    def create_time(mapper, connection, target):
        target.created = time()

    @classmethod
    def __declare_last__(cls):
        # get called after mappings are completed
        # http://docs.sqlalchemy.org/en/rel_0_7/orm/extensions/declarative.html#declare-last
        event.listen(cls, 'before_insert', cls.create_time)
于 2012-11-29T01:52:39.647 回答
16

这是我要监听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)

这样,您可以:

  1. 轻松扩展和更改您收听的内容和注册的内容。
  2. 覆盖某些类的 create_time 方法
  3. 明确哪些方法需要设置其时间戳。

您可以简单地使用它:

class MyMappedClass(TimeStampMixin, Base):
    pass

MyMappedClass.register()

简单,非常清晰,没有魔法,但仍然可以像你想要的那样封装。

于 2012-10-05T21:09:24.707 回答
4

现代 SqlAlchemy 中最好的方法是将@listens_for装饰器与propagate=True.

from datetime import datetime
from sqlalchemy import Column, Float
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.event import listens_for

class TimestampMixin():
    @declared_attr
    def created(cls):
        return Column(DateTime(timezone=True))

@listens_for(TimeStampMixin, "init", propagate=True)
def timestamp_init(target, args, kwargs):
    kwargs["created"] = datetime.utcnow()
于 2017-05-22T19:40:30.697 回答
3

你也可以这样做:

from sqlalchemy.orm.interfaces import MapperExtension

class BaseExtension(MapperExtension):
    """Base entension class for all entities """

    def before_insert(self, mapper, connection, instance):
        """ set the created_at  """
        instance.created = datetime.datetime.now()

    def before_update(self, mapper, connection, instance):
        """ set the updated_at  """
        instance.modified = datetime.datetime.now()


class TimeStampMixin(object):
    id = Column(Integer, primary_key=True, autoincrement=True)
    created = Column(DateTime())
    modified = Column(DateTime())

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8'
    }
    __mapper_args__ = { 'extension': BaseExtension() }

并定义你的类,如:

class User(TimeStampMixin, Base):
于 2012-10-06T17:04:59.723 回答