assets.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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,
  17. file=css,
  18. hash=get_file_hash(css),
  19. size=css.size,
  20. )
  21. def create_image(theme, image):
  22. if image_exists(theme, image):
  23. delete_image(theme, image)
  24. save_image(theme, image)
  25. def image_exists(theme, image):
  26. return theme.images.filter(name=image.name).exists()
  27. def delete_image(theme, image):
  28. theme.images.get(name=image.name).delete()
  29. def save_image(theme, image):
  30. theme.images.create(
  31. name=image.name,
  32. file=image,
  33. hash=get_file_hash(image),
  34. type=image.content_type,
  35. size=image.size,
  36. thumbnail=get_image_thumbnail(image),
  37. )
  38. def get_image_thumbnail(image):
  39. img = Image.open(image.file)
  40. img.thumbnail(IMAGE_THUMBNAIL_SIZE)
  41. file = io.BytesIO()
  42. img.save(file, format="png")
  43. img.close()
  44. filename = image.name.split('.')[0]
  45. return ImageFile(file, name='thumb_%s.png' % filename)
  46. def get_file_hash(file):
  47. if file.size is None:
  48. return "000000000000"
  49. file_hash = hashlib.md5()
  50. for chunk in file.chunks():
  51. file_hash.update(chunk)
  52. return file_hash.hexdigest()[:12]