Skip to content

Commit dacb5df

Browse files
committed
add caching to role query
1 parent 4ecef7a commit dacb5df

1 file changed

Lines changed: 12 additions & 1 deletion

File tree

api/views/auditor.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import logging
44
from typing import Any, Dict, List, Optional
55

6+
from django.core.cache import cache
67
from django.db import transaction
78
from rest_framework import status, views
89
from rest_framework.permissions import IsAuthenticated
@@ -12,6 +13,8 @@
1213
from api.models import Organization
1314
from authorization.models import OrganizationMembership, Role, User
1415

16+
ROLE_CACHE_TTL = 60 * 60 # 1 hour
17+
1518
logger = logging.getLogger(__name__)
1619

1720

@@ -46,8 +49,16 @@ def _check_admin_permission(self, user: User, organization: Organization) -> boo
4649

4750
def _get_auditor_role(self) -> Optional[Role]:
4851
"""Get the auditor role."""
52+
cached_id = cache.get("role_id:auditor")
53+
if cached_id:
54+
try:
55+
return Role.objects.get(pk=cached_id)
56+
except Role.DoesNotExist:
57+
cache.delete("role_id:auditor")
4958
try:
50-
return Role.objects.get(name="auditor")
59+
role = Role.objects.get(name="auditor")
60+
cache.set("role_id:auditor", role.pk, timeout=ROLE_CACHE_TTL)
61+
return role
5162
except Role.DoesNotExist:
5263
logger.error("Auditor role not found. Please run migrations.")
5364
return None

0 commit comments

Comments
 (0)