SQLAlchemy - 如何在提交列之前处理列?

时间:2017-02-17 23:10:13

标签: python orm insert sqlalchemy

我有一个简单的用户类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()

1 个答案:

答案 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)