clearattachments.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import time
  2. from datetime import timedelta
  3. from django.core.management.base import BaseCommand
  4. from django.utils import timezone
  5. from ....conf.shortcuts import get_dynamic_settings
  6. from ....core.management.progressbar import show_progress
  7. from ....core.pgutils import chunk_queryset
  8. from ...models import Attachment
  9. class Command(BaseCommand):
  10. help = "Deletes attachments unassociated with any posts"
  11. def handle(self, *args, **options):
  12. settings = get_dynamic_settings()
  13. cutoff = timezone.now() - timedelta(hours=settings.unused_attachments_lifetime)
  14. queryset = Attachment.objects.filter(post__isnull=True, uploaded_on__lt=cutoff)
  15. attachments_to_sync = queryset.count()
  16. if not attachments_to_sync:
  17. self.stdout.write("\n\nNo unused attachments were cleared")
  18. else:
  19. self.sync_attachments(queryset, attachments_to_sync)
  20. def sync_attachments(self, queryset, attachments_to_sync):
  21. self.stdout.write("Clearing %s attachments...\n" % attachments_to_sync)
  22. cleared_count = 0
  23. show_progress(self, cleared_count, attachments_to_sync)
  24. start_time = time.time()
  25. for attachment in chunk_queryset(queryset):
  26. attachment.delete()
  27. cleared_count += 1
  28. show_progress(self, cleared_count, attachments_to_sync, start_time)
  29. self.stdout.write("\n\nCleared %s attachments" % cleared_count)