forked from apluslms/a-plus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.py
65 lines (52 loc) · 2.03 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from django.db.models.signals import post_save, post_delete
from lib.cached import CachedAbstract
from .models import Notification
class CachedNotifications(CachedAbstract):
KEY_PREFIX = "notifications"
def __init__(self, user):
super().__init__(user)
def _generate_data(self, user, data=None):
if not user or not user.is_authenticated():
return {
'count': 0,
'notifications': [],
}
def notification_entry(n):
exercise = n.submission.exercise if n.submission else None
return {
'id': n.id,
'submission_id': n.submission.id if n.submission else 0,
'name': "{} {}, {}".format(
n.course_instance.course.code,
(str(exercise.parent)
if exercise and exercise.parent else
n.course_instance.instance_name),
(str(exercise)
if exercise else
n.subject),
),
'link': n.get_display_url(),
}
notifications = list(
user.userprofile.received_notifications\
.filter(seen=False)\
.select_related(
'submission',
'submission__exercise',
'course_instance',
'course_instance__course',
)
)
return {
'count': len(notifications),
'notifications': [notification_entry(n) for n in notifications],
}
def count(self):
return self.data['count']
def notifications(self):
return self.data['notifications']
def invalidate_notifications(sender, instance, **kwargs):
CachedNotifications.invalidate(instance.recipient.user)
# Automatically invalidate cache when notifications change.
post_save.connect(invalidate_notifications, sender=Notification)
post_delete.connect(invalidate_notifications, sender=Notification)