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 misago.conf import settings
  6. from misago.core.management.progressbar import show_progress
  7. from misago.core.pgutils import chunk_queryset
  8. from misago.threads.models import Attachment
  9. class Command(BaseCommand):
  10. help = "Deletes attachments unassociated with any posts"
  11. def handle(self, *args, **options):
  12. cutoff = timezone.now() - timedelta(
  13. minutes=settings.MISAGO_ATTACHMENT_ORPHANED_EXPIRE
  14. )
  15. queryset = Attachment.objects.filter(post__isnull=True, uploaded_on__lt=cutoff)
  16. attachments_to_sync = queryset.count()
  17. if not attachments_to_sync:
  18. self.stdout.write("\n\nNo attachments were found")
  19. else:
  20. self.sync_attachments(queryset, attachments_to_sync)
  21. def sync_attachments(self, queryset, attachments_to_sync):
  22. self.stdout.write("Clearing %s attachments...\n" % attachments_to_sync)
  23. cleared_count = 0
  24. show_progress(self, cleared_count, attachments_to_sync)
  25. start_time = time.time()
  26. for attachment in chunk_queryset(queryset):
  27. attachment.delete()
  28. cleared_count += 1
  29. show_progress(self, cleared_count, attachments_to_sync, start_time)
  30. self.stdout.write("\n\nCleared %s attachments" % cleared_count)