assets.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import hashlib
  2. import io
  3. from PIL import Image
  4. from django.core.files.images import ImageFile
  5. IMAGE_THUMBNAIL_SIZE = (32, 32)
  6. def create_css(theme, css):
  7. if css_exists(theme, css):
  8. delete_css(theme, css)
  9. save_css(theme, css)
  10. def css_exists(theme, css):
  11. return theme.css.filter(name=css.name).exists()
  12. def delete_css(theme, css):
  13. theme.css.get(name=css.name).delete()
  14. def save_css(theme, css):
  15. theme.css.create(
  16. name=css.name, source_file=css, source_hash=get_file_hash(css), size=css.size
  17. )
  18. def create_image(theme, image):
  19. if image_exists(theme, image):
  20. delete_image(theme, image)
  21. save_image(theme, image)
  22. def image_exists(theme, image):
  23. return theme.images.filter(name=image.name).exists()
  24. def delete_image(theme, image):
  25. theme.images.get(name=image.name).delete()
  26. def save_image(theme, image):
  27. theme.images.create(
  28. name=image.name,
  29. file=image,
  30. hash=get_file_hash(image),
  31. type=image.content_type,
  32. size=image.size,
  33. thumbnail=get_image_thumbnail(image),
  34. )
  35. def get_image_thumbnail(image):
  36. img = Image.open(image.file)
  37. img.thumbnail(IMAGE_THUMBNAIL_SIZE)
  38. file = io.BytesIO()
  39. img.save(file, format="png")
  40. img.close()
  41. filename = image.name.split(".")[0]
  42. return ImageFile(file, name="thumb_%s.png" % filename)
  43. def get_file_hash(file):
  44. if file.size is None:
  45. return "00000000"
  46. file_hash = hashlib.md5()
  47. for chunk in file.chunks():
  48. file_hash.update(chunk)
  49. return file_hash.hexdigest()[:8]