I know this should be a elementary question, but for some reason it doesn't make sense to me. I don't understand why the line db.session.commit()
isn't indented under the for statement for r in roles:
? Instead it's indented under the function definition def insert_roles():
, which to me doesn't make sense because nothing is happening until the for statement other than assigning the dict keys and values. I'll post the entire code and what the book says about it below. Thanks in advance for any help. . .
class Permission:
FOLLOW = 0x01
COMMENT = 0x02
WRITE_ARTICLES = 0x04
MODERATE_COMMENTS = 0x08
ADMINISTER = 0x80
class Role(db.Model):
__tablename__ = 'roles'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), unique=True)
default = db.Column(db.Boolean, default=False, index=True)
permissions = db.Column(db.Integer)
users = db.relationship('User', backref='role', lazy='dynamic')
@staticmethod
def insert_roles():
roles = {
'User': (Permission.FOLLOW |
Permission.COMMENT |
Permission.WRITE_ARTICLES, True),
'Moderator': (Permission.FOLLOW |
Permission.COMMENT |
Permission.WRITE_ARTICLES |
Permission.MODERATE_COMMENTS, False),
'Administrator': (0xff, False)
}
for r in roles:
role = Role.query.filter_by(name=r).first()
if role is None:
role = Role(name=r)
role.permissions = roles[r][0]
role.default = roles[r][1]
db.session.add(role)
db.session.commit()
def __repr__(self):
return '<Role %r>' % self.name
From the book:
The
insert_roles()
function does not directly create new role objects. Instead, it tries to find existing roles by name and update those. A new role object is created only for role names that aren’t in the database already. This is done so that the role list can be updated in the future when changes need to be made. To add a new role or change the permission assignments for a role, change the roles array and rerun the function. Note that the “Anonymous” role does not need to be represented in the database, as it is designed to represent users who are not in the database.