简体   繁体   中英

In Python Flask, how to get the role name by the current logged in user?

I have 3 tables for user-role many-to-many relationship in Flask. How should I get the role name from the current user?

In my models.py

class User(db.Model, UserMixin):
    __tablename__ = "Users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False, server_default='')

    # Define the relationship to Role via UserRoles
    roles = db.relationship('Role', secondary='UserRoles', backref=db.backref("user", lazy="dynamic"))


# Define the Role data-model
class Role(db.Model):
    __tablename__ = 'Roles'
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(50), unique=True)
    users = db.relationship('User', secondary='UserRoles', backref=db.backref("role", lazy="dynamic"))


# # Define the UserRoles association table
class UserRole(db.Model):
    __tablename__ = 'UserRoles'
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('Users.id', ondelete='CASCADE'))
    role_id = db.Column(db.Integer(), db.ForeignKey('Roles.id', ondelete='CASCADE'))

In my views.py:

from flask_user import current_user

@app.route("/TestUserRole")
def user_role():
    role = current_user.role
    return str(role)

On the browser, it shows me the returned result:

SELECT [Roles].id AS [Roles_id], [Roles].name AS [Roles_name] FROM [Roles], [UserRoles] WHERE [UserRoles].user_id = ? AND [Roles].id = [UserRoles].role_id

Is there a possible way to show the role name of the current user, something like the following (bad example, though, since it will pop out error)?

role = current_user.role.name

The current_user.has_roles function will help.

It is quite simple: Suppose you have configure below roles like

Role1: Admin

Role2: Manager

If user has no role associated then, current_user.has_roles() will be False.

If logged in user has a role of 'Admin', this can be verified using current_user.has_roles('Admin') .

So users roles can be accessed via has_roles() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM