blueblank blueblank - 1 year ago 79
Python Question

Sqlalchemy mixins / and event listener

I am attempting 2 new things at once, so assistance in both simplifying and clarifying is appreciated.

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)


So I want to create a mixin I can apply in any class:

class MyClass(TimeStampMixin, Base):
etc, etc, etc


This class inherits functionality that creates a timestamp on creation and creates/modifies a timestamp on update.

on import I get this error:

raise exc.UnmappedClassError(class_)
sqlalchemy.orm.exc.UnmappedClassError: Class 'db.database.TimeStampMixin' is not mapped


aaaand I'm stumped at this point.

Answer Source

Here's what I'd do to listen on before_insert events: add a classmethod to your TimeStampMixin that registers the current class and handles setting creation time.

E.g.

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)

That way, you can:

  1. Easily extend and change what you listen for and what you register.
  2. Override the create_time method for certain classes
  3. Be explicit about which methods need to have their timestamps set.

You can use it simply:

class MyMappedClass(TimeStampMixin, Base):
    pass

MyMappedClass.register()

Simple, very clear, no magic, but still encapsulates like you want.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download