fix(users): Reduce amount of SELECT queries in set_roles

This commit is contained in:
Ferdinand Thiessen 2021-12-18 01:52:35 +01:00
parent ec7bf39666
commit 9f6aa38925
1 changed files with 7 additions and 9 deletions

View File

@ -90,15 +90,13 @@ def update_user(user):
db.session.commit()
def set_roles(user: User, roles: list[str], create=False):
user.roles_.clear()
for role_name in roles:
role = Role.query.filter(Role.name == role_name).one_or_none()
if not role:
if not create:
raise BadRequest("Role not found >{}<".format(role_name))
role = Role(name=role_name)
user.roles_.append(role)
def set_roles(user: User, roles: list[str]):
if not isinstance(roles, list) and any([not isinstance(r, str) for r in roles]):
raise BadRequest("Invalid role name")
fetched = Role.query.filter(Role.name.in_(roles)).all()
if len(fetched) < len(roles):
raise BadRequest("Invalid role name, role not found")
user.roles_ = fetched
def modify_user(user, password, new_password=None):