clearattachments.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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(minutes=settings.MISAGO_ATTACHMENT_ORPHANED_EXPIRE)
  13. queryset = Attachment.objects.filter(
  14. post__isnull=True,
  15. uploaded_on__lt=cutoff,
  16. )
  17. attachments_to_sync = queryset.count()
  18. if not attachments_to_sync:
  19. self.stdout.write("\n\nNo attachments were found")
  20. else:
  21. self.sync_attachments(queryset, attachments_to_sync)
  22. def sync_attachments(self, queryset, attachments_to_sync):
  23. self.stdout.write("Clearing %s attachments...\n" % attachments_to_sync)
  24. cleared_count = 0
  25. show_progress(self, cleared_count, attachments_to_sync)
  26. start_time = time.time()
  27. for attachment in chunk_queryset(queryset):
  28. attachment.delete()
  29. cleared_count += 1
  30. show_progress(self, cleared_count, attachments_to_sync, start_time)
  31. self.stdout.write("\n\nCleared %s attachments" % cleared_count)