models: Cache currently_used_upload_space_bytes function.

This commit is contained in:
Vishnu Ks
2019-01-14 12:16:31 +05:30
committed by Tim Abbott
parent cc9f00f53e
commit 94ae2dc24e
3 changed files with 33 additions and 1 deletions

View File

@@ -20,7 +20,8 @@ from zerver.lib.cache import cache_with_key, flush_user_profile, flush_realm, \
display_recipient_cache_key, cache_delete, active_user_ids_cache_key, \
get_stream_cache_key, realm_user_dicts_cache_key, \
bot_dicts_in_realm_cache_key, realm_user_dict_fields, \
bot_dict_fields, flush_message, flush_submessage, bot_profile_cache_key
bot_dict_fields, flush_message, flush_submessage, bot_profile_cache_key, \
flush_used_upload_space_cache, get_realm_used_upload_space_cache_key
from zerver.lib.utils import make_safe_digest, generate_random_token
from django.db import transaction
from django.utils.timezone import now as timezone_now
@@ -394,6 +395,7 @@ class Realm(models.Model):
# it as gibibytes (GiB) to be a bit more generous in case of confusion.
return self.upload_quota_gb << 30
@cache_with_key(get_realm_used_upload_space_cache_key, timeout=3600*24*7)
def currently_used_upload_space_bytes(self) -> int:
used_space = Attachment.objects.filter(realm=self).aggregate(Sum('size'))['size__sum']
if used_space is None:
@@ -1750,6 +1752,9 @@ class Attachment(AbstractAttachment):
} for m in self.messages.all()]
}
post_save.connect(flush_used_upload_space_cache, sender=Attachment)
post_delete.connect(flush_used_upload_space_cache, sender=Attachment)
def validate_attachment_request(user_profile: UserProfile, path_id: str) -> Optional[bool]:
try:
attachment = Attachment.objects.get(path_id=path_id)