Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cleanup_mail.py 1.4KB

1234567891011121314151617181920212223242526272829303132333435
  1. import datetime
  2. from django.core.management.base import BaseCommand
  3. from django.utils.timezone import now
  4. from ...models import Attachment, Email
  5. class Command(BaseCommand):
  6. help = 'Place deferred messages back in the queue.'
  7. def add_arguments(self, parser):
  8. parser.add_argument('-d', '--days',
  9. type=int, default=90,
  10. help="Cleanup mails older than this many days, defaults to 90.")
  11. parser.add_argument('-da', '--delete-attachments', action='store_true',
  12. help="Delete orphaned attachments.")
  13. def handle(self, verbosity, days, delete_attachments, **options):
  14. # Delete mails and their related logs and queued created before X days
  15. cutoff_date = now() - datetime.timedelta(days)
  16. count = Email.objects.filter(created__lt=cutoff_date).count()
  17. Email.objects.only('id').filter(created__lt=cutoff_date).delete()
  18. print("Deleted {0} mails created before {1} ".format(count, cutoff_date))
  19. if delete_attachments:
  20. attachments = Attachment.objects.filter(emails=None)
  21. attachments_count = len(attachments)
  22. for attachment in attachments:
  23. # Delete the actual file
  24. attachment.file.delete()
  25. attachments.delete()
  26. print("Deleted {0} attachments".format(attachments_count))