clearattachments.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 batch_update
  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. message = "Clearing %s attachments...\n"
  24. self.stdout.write(message % attachments_to_sync)
  25. message = "\n\nCleared %s attachments"
  26. synchronized_count = 0
  27. show_progress(self, synchronized_count, attachments_to_sync)
  28. start_time = time.time()
  29. for attachment in batch_update(queryset):
  30. attachment.delete()
  31. synchronized_count += 1
  32. show_progress(self, synchronized_count, attachments_to_sync, start_time)
  33. self.stdout.write(message % synchronized_count)