Mercurial > public > sg101
comparison downloads/management/commands/dlorphan.py @ 665:86d04190ff4e
For issue #43, create mgmt. command to cleanup orphan downloads.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Fri, 24 May 2013 23:42:49 -0500 |
parents | |
children | 264b08bce8b8 |
comparison
equal
deleted
inserted
replaced
664:929d0e637a37 | 665:86d04190ff4e |
---|---|
1 """dlorphan - a management command to remove orphaned downloads files.""" | |
2 | |
3 from optparse import make_option | |
4 import os | |
5 | |
6 from django.core.management.base import NoArgsCommand | |
7 from django.conf import settings | |
8 | |
9 from downloads.models import Download, PendingDownload | |
10 | |
11 | |
12 class Command(NoArgsCommand): | |
13 help = "Finds and optionally deletes orphan downloads files" | |
14 option_list = NoArgsCommand.option_list + ( | |
15 make_option('--delete', | |
16 action='store_true', | |
17 dest='delete', | |
18 default=False, | |
19 help='Delete orphan files'), | |
20 ) | |
21 | |
22 def handle_noargs(self, **options): | |
23 """Find and optionally delete orphan downloads files.""" | |
24 | |
25 delete = options.get('delete', False) | |
26 | |
27 orphans = set() | |
28 missing_pending = [] | |
29 missing_dls = [] | |
30 empty_dirs = [] | |
31 | |
32 dls_dir = os.path.join(settings.MEDIA_ROOT, 'downloads') | |
33 # find the set of all files in the downloads area | |
34 for root, dirs, files in os.walk(dls_dir, followlinks=True): | |
35 for name in files: | |
36 orphans.add(unicode(os.path.join(root, name), 'utf-8')) | |
37 | |
38 # check for empty directories | |
39 if not len(dirs) and not len(files): | |
40 empty_dirs.append(root) | |
41 | |
42 # examine the pending downloads: | |
43 for dl in PendingDownload.objects.iterator(): | |
44 try: | |
45 orphans.remove(dl.file.path) | |
46 except KeyError: | |
47 missing_pending.append(dl) | |
48 | |
49 # examine the downloads: | |
50 for dl in Download.objects.iterator(): | |
51 try: | |
52 orphans.remove(dl.file.path) | |
53 except KeyError: | |
54 missing_dls.append(dl) | |
55 | |
56 if orphans: | |
57 print "Orphan files:" | |
58 for orphan in orphans: | |
59 print orphan | |
60 | |
61 if empty_dirs: | |
62 print "Empty directories:" | |
63 for d in empty_dirs: | |
64 print d | |
65 | |
66 if missing_pending: | |
67 print "PendingDownloads with missing files:" | |
68 for dl in missing_pending: | |
69 print dl | |
70 | |
71 if missing_dls: | |
72 print "Downloads with missing files:" | |
73 for dl in missing_dls: | |
74 print dl | |
75 | |
76 if delete: | |
77 for path in orphans: | |
78 print "Deleting: {}".format(path) | |
79 os.remove(path) | |
80 | |
81 for path in empty_dirs: | |
82 print "Deleting: {}".format(path) | |
83 os.removedirs(path) |