Просмотр исходного кода

Prune orphaned attachments maintenance task. #29

Rafał Pitoń 11 лет назад
Родитель
Сommit
24afc10dfa
3 измененных файлов с 31 добавлено и 0 удалено
  1. 1 0
      cron.txt
  2. 22 0
      misago/management/commands/pruneattachments.py
  3. 8 0
      misago/models/attachmentmodel.py

+ 1 - 0
cron.txt

@@ -1,5 +1,6 @@
 0 3 * * * python $HOME/misago/manage.py clearalerts
 0 3 * * * python $HOME/misago/manage.py clearattempts
+0 3 * * * python $HOME/misago/manage.py pruneattachments
 0 */4 * * * python $HOME/misago/manage.py clearsessions
 20 3 * * * python $HOME/misago/manage.py cleartokens
 15 3 * * * python $HOME/misago/manage.py cleartracker

+ 22 - 0
misago/management/commands/pruneattachments.py

@@ -0,0 +1,22 @@
+from datetime import timedelta
+from django.core.management.base import BaseCommand
+from django.utils import timezone
+from misago.models import Attachment
+
+class Command(BaseCommand):
+    """
+    Prune Attachments
+    This command removes attachments that were uploaded but not attached to any posts.
+    """
+    help = 'Prune orphaned attachments'
+    def handle(self, *args, **options):
+        date_cutoff = timezone.now() - timedelta(days=1)
+        deleted_count = 0
+        for attachment in Attachment.objects.filter(date__lt=date_cutoff).filter(post__isnull=True).iterator():
+            attachment.delete()
+            deleted_count += 1
+
+        if deleted_count == 1:
+            self.stdout.write('One orphaned attachment has been deleted.\n')
+        else:
+            self.stdout.write('%s orphaned attachments have been deleted.\n' % deleted_count)

+ 8 - 0
misago/models/attachmentmodel.py

@@ -50,8 +50,16 @@ class Attachment(models.Model):
                 thumb_path.unlink()
         except Exception:
             pass
+
         super(Attachment, self).delete(*args, **kwargs)
 
+    def delete_from_post(self):
+        if self.post_id:
+            self.post.attachments = [attachment
+                                     for attachment in self.post.attachments
+                                     if attachment.pk != self.pk]
+            self.post.save(force_update=True)
+
     @property
     def is_image(self):
         IMAGES_EXTENSIONS = ('.png', '.gif', '.jpg', '.jpeg')