vbv/server/vbv_lernwelt/files/management/commands/delete_unreferenced_files.py

50 lines
1.4 KiB
Python

from django.core.management.base import BaseCommand
from vbv_lernwelt.files.models import UploadFile
class Command(BaseCommand):
help = "Delete unreferenced uploads and delete their files"
def add_arguments(self, parser):
parser.add_argument(
"--dry-run",
action="store_true",
dest="dry_run",
default=False,
help="Dry run",
)
def handle(self, *args, **options):
dry_run = options["dry_run"]
num_deleted = 0
unreferenced_uploads = UploadFile.objects.filter(
upload_finished_at__isnull=True
)
if dry_run:
print("------ DRY RUN -------")
print(
"Going to delete {} unreferenced uploads".format(
unreferenced_uploads.count()
)
)
for upload in unreferenced_uploads:
try:
if not dry_run:
upload.delete_file()
file_id = upload.id
upload.delete()
print("Deleted file with id {}".format(file_id))
else:
print("Would delete file with id {}".format(upload.id))
num_deleted += 1
except Exception as e:
print(e)
pass
print("Deleted {:d} uploads".format(num_deleted))