【问题标题】:SQLAlchemy - How to process a column before it is committed?SQLAlchemy - 如何在提交之前处理列?
【发布时间】:2017-07-07 15:08:03
【问题描述】:

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

如何修改我的 User 类或监听事件,以便在密码提交之前将密码更改为加盐版本?而不是每次都做user.name = salted(username),我希望它以某种方式内置到用户类中。

user = User(name='test', password='hashme')
Session = sessionmaker(bind=engine) # get a factory
mySession = Session()
mySession.add(user)
mySession.commit()

【问题讨论】:

    标签: python orm insert sqlalchemy


    【解决方案1】:
    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)
    

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 1970-01-01
      • 2012-04-22
      • 2015-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多