Mercurial > public > sg101
comparison bio/management/commands/avatar_cleanup.py @ 668:644f69e1c1e1
For issue #42, create avatar cleanup script.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 25 May 2013 15:17:42 -0500 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
667:264b08bce8b8 | 668:644f69e1c1e1 |
---|---|
1 """avatar_cleanup - a management command to remove orphaned avatar 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 bio.models import UserProfile | |
10 | |
11 | |
12 class Command(NoArgsCommand): | |
13 help = "Finds and optionally deletes orphan avatar 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 avatar files.""" | |
24 | |
25 delete = options.get('delete', False) | |
26 | |
27 orphans = set() | |
28 missing = [] | |
29 | |
30 avatar_dir = os.path.join(settings.MEDIA_ROOT, settings.AVATAR_DIR) | |
31 default_avatar = os.path.join(avatar_dir, | |
32 settings.AVATAR_DEFAULT_URL.split('/')[-1]) | |
33 | |
34 # find the set of all files in the downloads area | |
35 for root, dirs, files in os.walk(avatar_dir, followlinks=True): | |
36 for name in files: | |
37 orphans.add(unicode(os.path.join(root, name), 'utf-8')) | |
38 | |
39 try: | |
40 orphans.remove(default_avatar) | |
41 except KeyError: | |
42 self.stderr.write("Default avatar file missing! - {}\n".format( | |
43 default_avatar)) | |
44 | |
45 # examine the UserProfile objects | |
46 for profile in UserProfile.objects.iterator(): | |
47 if profile.avatar: | |
48 try: | |
49 orphans.remove(profile.avatar.path) | |
50 except KeyError: | |
51 missing.append(profile) | |
52 | |
53 if orphans and delete: | |
54 for path in orphans: | |
55 self.stdout.write("Deleting: {}\n".format(path)) | |
56 os.remove(path) | |
57 elif orphans: | |
58 self.stdout.write("Orphan files:\n") | |
59 for orphan in orphans: | |
60 self.stdout.write("{}\n".format(orphan)) | |
61 | |
62 if missing: | |
63 self.stdout.write("Users with missing avatar files:\n") | |
64 for profile in missing: | |
65 self.stdout.write("{}\n".format(profile.user.username)) | |
66 | |
67 empty_dirs = [] | |
68 # check for empty directories after deletions | |
69 for root, dirs, files in os.walk(avatar_dir, followlinks=True): | |
70 if not len(dirs) and not len(files): | |
71 empty_dirs.append(root) | |
72 | |
73 if empty_dirs and delete: | |
74 for path in empty_dirs: | |
75 self.stdout.write("Deleting empty dir: {}\n".format(path)) | |
76 os.removedirs(path) | |
77 elif empty_dirs: | |
78 self.stdout.write("Empty directories:\n") | |
79 for d in empty_dirs: | |
80 self.stdout.write("{}\n".format(d)) |