如何使用信号允许Flask-user中具有相同角色的许多用户

时间:2017-08-14 12:41:30

标签: python flask

我正在使用flask-user创建一个允许具有不同角色的多个用户的webapp。 在我当前的实施中,当用户创建帐户时,使用flask signals

将与用户相关的名称为 account_owner 的角色添加到数据库中

使用我当前的实现,只能为一个用户添加一个角色。 在添加具有相同角色的其他用户时遇到问题。

这是我的信号代码:

from app.models import User, Role, UserRoles
from flask_user import user_registered

@user_registered.connect_via(app)
def _after_register_hook(sender, user, **extra):
    idd = user.id
    rl = "account_owner"
    #check if the role exists
    if not Role.query.filter_by(name = rl).first():
        #if not, add the user with the role.
        if User.query.filter_by(id = idd).first():
            updt = User.query.filter_by(id = idd).first()
            updt.roles.append(Role(name = rl))
            db.session.commit()
            flash('role added')
            return redirect(url_for('home.index'))
    #(this is implemented from the second user)if the role exists, add the user to the UseRoles list for the first role. 
    else:
        UserRoles(user_id=user.id, role_id=1)
        flash('role added')
        return redirect(url_for('home.index'))

我的数据库模型是:

class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)

        # User authentication information
        username = db.Column(db.String(50), nullable=False, unique=True)
        password = db.Column(db.String(255), nullable=False, server_default='')
        reset_password_token = db.Column(db.String(100), nullable=False, server_default='')

        # User email information
        email = db.Column(db.String(255), nullable=False, unique=True)
        confirmed_at = db.Column(db.DateTime())

        # User information
        active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0')

        #Relationships
        roles = db.relationship('Role', secondary='user_roles',backref=db.backref('users', lazy='dynamic'))

# Define the Role data model
class Role(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        name = db.Column(db.String(50), unique=True)

# Define the UserRoles data model
class UserRoles(db.Model):
        id = db.Column(db.Integer(), primary_key=True)
        user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
        role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))

1 个答案:

答案 0 :(得分:0)

如果角色存在,则不会向数据库添加和提交UserRole。你的代码的逻辑并不清楚。

from app.models import User, Role, UserRole
from flask_user import user_registered

@user_registered.connect_via(app)
def after_register_hook(sender, user, **extra):

    role = Role.query.filter_by(name="account_owner").first()

    if role is None:  # just check if the role is existed, if not ,create it. You'd better to create the role in the initial process of the applicaiton.
        role = Role(name="account_owner")
        db.session.add(role)
        db.session.commit()

    # You needn't to check the existence of the user.

    user_role = UserRole(user_id=user.id, role_id=role.id)
    db.session.add(user_role)
    db.session.commit()

    flash("role added.")
    return redirect(url_for("home.index"))