From dc7b2f076201b17d0aac86ebcb30ce330ccc8b31 Mon Sep 17 00:00:00 2001 From: Calen Pennington Date: Fri, 6 Jun 2014 12:30:29 -0400 Subject: [PATCH] Don't create model objects to check the roles cache --- common/djangoapps/student/roles.py | 37 ++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/common/djangoapps/student/roles.py b/common/djangoapps/student/roles.py index 6c56b934b9..640b7cd703 100644 --- a/common/djangoapps/student/roles.py +++ b/common/djangoapps/student/roles.py @@ -10,6 +10,27 @@ from student.models import CourseAccessRole from xmodule_django.models import CourseKeyField +class RoleCache(object): + """ + A cache of the CourseAccessRoles held by a particular user + """ + def __init__(self, user): + self._roles = set( + CourseAccessRole.objects.filter(user=user).all() + ) + + def has_role(self, role, course_id, org): + """ + Return whether this RoleCache contains a role with the specified role, course_id, and org + """ + return any( + access_role.role == role and + access_role.course_id == course_id and + access_role.org == org + for access_role in self._roles + ) + + class AccessRole(object): """ Object representing a role with particular access to a resource @@ -94,12 +115,11 @@ class RoleBase(AccessRole): # pylint: disable=protected-access if not hasattr(user, '_roles'): - user._roles = set( - CourseAccessRole.objects.filter(user=user).all() - ) + # Cache a list of tuples identifying the particular roles that a user has + # Stored as tuples, rather than django models, to make it cheaper to construct objects for comparison + user._roles = RoleCache(user) - role = CourseAccessRole(user=user, role=self._role_name, course_id=self.course_key, org=self.org) - return role in user._roles + return user._roles.has_role(self._role_name, self.course_key, self.org) def add_users(self, *users): """ @@ -232,12 +252,9 @@ class UserBasedRole(object): # pylint: disable=protected-access if not hasattr(self.user, '_roles'): - self.user._roles = list( - CourseAccessRole.objects.filter(user=self.user).all() - ) + self.user._roles = RoleCache(self.user) - role = CourseAccessRole(user=self.user, role=self.role, course_id=course_key, org=course_key.org) - return role in self.user._roles + return self.user._roles.has_role(self.role, course_key, course_key.org) def add_course(self, *course_keys): """