如何使用sqlalchemy添加默认相关记录(例如,用户属于组)

时间:2011-08-06 13:35:07

标签: sqlalchemy

我有两个模型:AuthUser和AuthGroup,它们通过many2many关系链接。默认情况下,我至少有3个用户“状态”:

  • unlogged - >没有小组
  • 已登录 - >用户组
  • admin - >管理组

我想确保无论何时将新用户添加到数据库,它都会添加到用户组。有没有办法在模型定义中获得此功能?

这是我的表格定义

Base = declarative_base()

user_group_table = Table('auth_user_groups', Base.metadata,
    Column('user_id', types.Integer(), \
        ForeignKey('auth_users.id', onupdate='CASCADE', ondelete='CASCADE')),
    Column('group_id', types.Integer(), \
        ForeignKey('auth_groups.id', onupdate='CASCADE', ondelete='CASCADE'))
)

class AuthGroup(Base):
    __tablename__ = 'auth_groups'
    __table_args__ = {"sqlite_autoincrement": True}


    id = Column(types.Integer(), primary_key=True)
    name = Column(Unicode(80), unique=True, nullable=False)
    created = Column(types.DateTime(), default=functions.now())

    users = relation('AuthUser', secondary=user_group_table, \
                     backref='auth_groups')

    def __repr__(self):
        return u'%s' % self.name

    def __unicode__(self):
        return self.name


class AuthUser(Base):
    __tablename__ = 'auth_users'
    __table_args__ = {"sqlite_autoincrement": True}

    id = Column(types.Integer(), primary_key=True)
    login = Column(Unicode(80), default=u'', index=True)
    username = Column(Unicode(80), default=u'', index=True)
    _password = Column('password', Unicode(80), default=u'', index=True)
    email = Column(Unicode(80), default=u'', index=True)

    groups = relation('AuthGroup', secondary=user_group_table, \
                      backref='auth_users')

    def _set_password(self, password):
        self._password = bcrypt.hashpw(password, bcrypt.gensalt())

    def _get_password(self):
        return self._password

    password = synonym('_password', descriptor=property(_get_password, \
                       _set_password))

    @classmethod
    def get_by_id(cls, id):
        return DBSession.query(cls).filter(cls.id==id).first()    

    @classmethod
    def get_by_login(cls, login):
        return DBSession.query(cls).filter(cls.login==login).first()

    @classmethod
    def get_by_username(cls, username):
        return DBSession.query(cls).filter(cls.username==username).first()

    @classmethod
    def get_by_email(cls, email):
        return DBSession.query(cls).filter(cls.email==email).first()

    @classmethod
    def check_password(cls, **kwargs):
        if kwargs.has_key('id'):
            user = cls.get_by_id(kwargs['id'])
        if kwargs.has_key('username'):
            user = cls.get_by_username(kwargs['username'])

        if not user:
            return False
        if bcrypt.hashpw(kwargs['password'], user.password) == user.password:
            return True
        else:
            return False

1 个答案:

答案 0 :(得分:0)

通常一个类构造函数在创建新对象时验证期望的数据(ORM中的INSERT,缺少任何绕过通常机制的技巧,总是对应于通过构造函数创建的映射类的新实例):

class AuthUser(Base):
    def __init__(self, **kw):
        self.groups = kw.pop('groups', None)
        if not self.groups:
            raise ValueError("at least one group is required!")
        super(AuthUser, self).__init__(**kw)