Commit 090ade50 authored by chris's avatar chris
Browse files

Added a dryrun option to the cleanup command. Fixed minor bug in content

read caused by partially pre-read file object.
parent a5dae1ca
VERSION = (0, 1, 6) VERSION = (0, 1, 7)
__version__ = '.'.join(map(str, VERSION)) __version__ = '.'.join(map(str, VERSION))
\ No newline at end of file
import os import os
from optparse import make_option
from django.conf import settings from django.conf import settings
from django.core.files.storage import default_storage from django.core.files.storage import default_storage
...@@ -11,11 +12,20 @@ class Command(BaseCommand): ...@@ -11,11 +12,20 @@ class Command(BaseCommand):
args = '' args = ''
help = 'Deletes all files in the database that are not referenced by ' + \ help = 'Deletes all files in the database that are not referenced by ' + \
'any model fields.' 'any model fields.'
option_list = BaseCommand.option_list + (
make_option('--dryrun',
action='store_true',
dest='dryrun',
default=False,
help='If given, only displays the names of orphaned files ' + \
'and does not delete them.'),
)
def handle(self, *args, **options): def handle(self, *args, **options):
tmp_debug = settings.DEBUG tmp_debug = settings.DEBUG
settings.DEBUG = False settings.DEBUG = False
names = set() names = set()
dryrun = options['dryrun']
try: try:
for model in get_models(): for model in get_models():
for field in model._meta.fields: for field in model._meta.fields:
...@@ -33,8 +43,14 @@ class Command(BaseCommand): ...@@ -33,8 +43,14 @@ class Command(BaseCommand):
names.add(file.name) names.add(file.name)
# Find all database files with names not in our list. # Find all database files with names not in our list.
orphan_files = File.objects.exclude(name__in=names) orphan_files = File.objects.exclude(name__in=names)
total_bytes = 0
for f in orphan_files: for f in orphan_files:
print 'Deleting %s...' % (f.name,) total_bytes += f.size
default_storage.delete(f.name) if dryrun:
print 'File %s is orphaned.' % (f.name,)
else:
print 'Deleting orphan file %s...' % (f.name,)
default_storage.delete(f.name)
print '%i total bytes in orphan files.' % total_bytes
finally: finally:
settings.DEBUG = tmp_debug settings.DEBUG = tmp_debug
...@@ -58,6 +58,7 @@ class DatabaseStorage(FileSystemStorage): ...@@ -58,6 +58,7 @@ class DatabaseStorage(FileSystemStorage):
size = content.size size = content.size
except AttributeError: except AttributeError:
size = os.path.getsize(full_path) size = os.path.getsize(full_path)
content.seek(0)
content = content.read() content = content.read()
f = models.File.objects.create( f = models.File.objects.create(
content=content, content=content,
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment