Respect max notification count for logging notifications.

Use a Q query to identify users for logging notifications. Should be much faster.
http://stackoverflow.com/questions/378303/how-to-get-a-list-of-all-users-with-a-specific-permission-group-in-django

Closes #576
This commit is contained in:
Adarnof 2016-11-13 17:11:24 -05:00
parent 97743cfe16
commit ea4fd12996
2 changed files with 24 additions and 14 deletions

View File

@ -9,7 +9,7 @@ MAX_NOTIFICATIONS = 50
def notify(user, title, message=None, level='info'):
from .models import Notification
if Notification.objects.filter(user=user).count() > MAX_NOTIFICATIONS:
for n in Notification.objects.filter(user=user)[MAX_NOTIFICATIONS:]:
for n in Notification.objects.filter(user=user)[MAX_NOTIFICATIONS-1:]:
n.delete()
notif = Notification()
notif.user = user

View File

@ -6,17 +6,27 @@ logger = logging.getLogger(__name__)
class NotificationHandler(logging.Handler):
def emit(self, record):
from django.contrib.auth.models import User
from django.contrib.auth.models import User, Permission
from django.db.models import Q
from notifications import notify
from notifications.models import Notification
for user in User.objects.all():
if user.has_perm('auth.logging_notifications'):
notif = Notification()
notif.user = user
notif.title = "%s [%s:%s]" % (record.levelname, record.funcName, record.lineno)
notif.level = str([item[0] for item in Notification.LEVEL_CHOICES if item[1] == record.levelname][0])
message = record.getMessage()
if record.exc_text:
message += "\n\n"
message = message + record.exc_text
notif.message = message
notif.save()
try:
perm = Permission.objects.get(codename="logging_notifications")
message = record.getMessage()
if record.exc_text:
message += "\n\n"
message = message + record.exc_text
users = User.objects.filter(Q(groups__permissions=perm) | Q(user_permissions=perm) | Q(is_superuser=True)).distinct()
for user in users:
notify(
user,
"%s [%s:%s]" % (record.levelname, record.funcName, record.lineno),
level = str([item[0] for item in Notification.LEVEL_CHOICES if item[1] == record.levelname][0]),
message = message
)
except Permission.DoesNotExist:
pass