我有一个简单的用户类http://docs.sqlalchemy.org/en/latest/orm/tutorial.html
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(Text)
password = Column(Text) # should be a hash
我如何能够moidyf我的User类或监听一个事件,以便我可以在提交之前将密码更改为salted版本?而不是每次都做user.name = salted(username)
,我希望它以某种方式构建到User类中。
user = User(name='test', password='hashme')
Session = sessionmaker(bind=engine) # get a factory
mySession = Session()
mySession.add(user)
mySession.commit()
答案 0 :(得分:2)
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(Text)
password = Column(Text) # should be a hash
@staticmethod
def _hash_password(mapper, connection, target):
user = target
user.password = hash_method(user.password)
listen(User, 'before_insert', User._hash_password)
listen(User, 'before_update', User._hash_password)