pyconjp2011 / models / pyconjp2011 / models / __init__.py

import hashlib
import itertools
import sqlalchemy as sa
import sqlalchemy.orm as orm
import sqlahelper

Base = sqlahelper.get_base()
DBSession = sqlahelper.get_session()

def init_db(engine):
    DBSession.remove()
    sqlahelper.add_engine(engine)

def create_all():
    Base.metadata.create_all(bind=DBSession.bind)

user_group = sa.Table('users_groups', Base.metadata,
        sa.Column('user_id', sa.Integer, sa.ForeignKey('users.id')),
        sa.Column('group_id', sa.Integer, sa.ForeignKey('groups.id')),
        )

group_permission = sa.Table('groups_permissions', Base.metadata,
        sa.Column('group_id', sa.Integer, sa.ForeignKey('groups.id')),
        sa.Column('permission_id', sa.Integer, sa.ForeignKey('permissions.id')),
        )

class User(Base):
    __tablename__ = 'users'
    id = sa.Column(sa.Integer, primary_key=True)
    user_name = sa.Column(sa.String, unique=True, nullable=False)
    _password = sa.Column("password", sa.String)
    groups = orm.relationship("Group", 
            secondary=user_group, backref="users")

    def get_permissions(self):
        return itertools.chain(*(g.permissions for g in self.groups))

    permissions = property(fget=get_permissions)

    def set_password(self, password):
        self._password = hashlib.sha1(password).hexdigest()

    password = property(fset=set_password)

    def validate_password(self, password):
        return self._password == hashlib.sha1(password).hexdigest()

class Group(Base):
    __tablename__ = 'groups'
    id = sa.Column(sa.Integer, primary_key=True)
    group_name = sa.Column(sa.String, unique=True)
    permissions = orm.relationship('Permission',
            secondary=group_permission, backref="groups")

    def __repr__(self):
        return self.group_name.encode('utf-8')

class Permission(Base):
    __tablename__ = 'permissions'
    id = sa.Column(sa.Integer, primary_key=True)
    permission_name = sa.Column(sa.String, unique=True)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.