easy_thumbnails.management.commands.thumbnail_cleanup: 48 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/easy_thumbnails/management/commands/thumbnail_cleanup.py

Stats: 0 executed, 42 missed, 6 excluded, 27 ignored

  1. import os
  2. import re
  3. from django.db import models
  4. from django.core.management.base import NoArgsCommand
  5. from easy_thumbnails.conf import settings
  6. try:
  7. set
  8. except NameError:
  9. from sets import Set as set # For Python 2.3
  10. thumb_re = re.compile(r'^%s(.*)\.\d{1,}x\d{1,}_[-\w]*q([1-9]\d?|100)\.jpg' %
  11. settings.THUMBNAIL_PREFIX)
  12. def get_thumbnail_path(path):
  13. basedir = settings.THUMBNAIL_BASEDIR
  14. subdir = settings.THUMBNAIL_SUBDIR
  15. return os.path.join(basedir, path, subdir)
  16. def clean_up():
  17. paths = set()
  18. for app in models.get_apps():
  19. model_list = models.get_models(app)
  20. for model in model_list:
  21. for field in model._meta.fields:
  22. if isinstance(field, models.ImageField):
  23. #TODO: take care of date formatted and callable upload_to.
  24. if (not callable(field.upload_to) and
  25. field.upload_to.find("%") == -1):
  26. paths = paths.union((field.upload_to,))
  27. paths = list(paths)
  28. for path in paths:
  29. thumbnail_path = get_thumbnail_path(path)
  30. try:
  31. file_list = os.listdir(os.path.join(settings.MEDIA_ROOT,
  32. thumbnail_path))
  33. except OSError:
  34. continue # Dir doesn't exists, no thumbnails here.
  35. for fn in file_list:
  36. m = thumb_re.match(fn)
  37. if m:
  38. # Due to that the naming of thumbnails replaces the dot before
  39. # extension with an underscore we have 2 possibilities for the
  40. # original filename. If either present we do not delete
  41. # suspected thumbnail.
  42. # org_fn is the expected original filename w/o extension
  43. # org_fn_alt is the expected original filename with extension
  44. org_fn = m.group(1)
  45. org_fn_exists = os.path.isfile(
  46. os.path.join(settings.MEDIA_ROOT, path, org_fn))
  47. usc_pos = org_fn.rfind("_")
  48. if usc_pos != -1:
  49. org_fn_alt = "%s.%s" % (org_fn[0:usc_pos],
  50. org_fn[usc_pos + 1:])
  51. org_fn_alt_exists = os.path.isfile(
  52. os.path.join(settings.MEDIA_ROOT, path, org_fn_alt))
  53. else:
  54. org_fn_alt_exists = False
  55. if not org_fn_exists and not org_fn_alt_exists:
  56. del_me = os.path.join(settings.MEDIA_ROOT,
  57. thumbnail_path, fn)
  58. os.remove(del_me)
  59. class Command(NoArgsCommand):
  60. help = "Deletes thumbnails that no longer have an original file."
  61. requires_model_validation = False
  62. def handle_noargs(self, **options):
  63. clean_up()