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.
Here’s what I’d do to listen on
before_insertevents: add aclassmethodto yourTimeStampMixinthat registers the current class and handles setting creation time.E.g.
That way, you can:
You can use it simply:
Simple, very clear, no magic, but still encapsulates like you want.