Guest User

Untitled

a guest
Dec 16th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import os
  2. from io import BytesIO
  3.  
  4. import boto3
  5. from PIL import Image
  6. from django.conf import settings
  7.  
  8.  
  9. def store_in_bucket(data, key, content_type, public_read=False):
  10. boto3.client('s3').put_object(
  11. Bucket=settings.STORAGE_BUCKET,
  12. Key=key,
  13. ContentType=content_type,
  14. ACL=('public-read' if public_read else 'private'),
  15. Body=data
  16. )
  17.  
  18.  
  19. def store_file_in_bucket(fileobj, key, public_read=False):
  20. boto3.client('s3').upload_fileobj(
  21. fileobj, settings.STORAGE_BUCKET, key,
  22. ExtraArgs=dict(
  23. ContentType=guess_content_type(fileobj),
  24. ContentDisposition='inline; filename="{}"'.format(fileobj.name),
  25. ACL=('public-read' if public_read else 'private')
  26. )
  27. )
  28.  
  29.  
  30. def get_bucket_object(key):
  31. return boto3.resource('s3').Object(settings.STORAGE_BUCKET, key)
  32.  
  33.  
  34. def get_signed_bucket_url(key, expire_minutes=10):
  35. return boto3.client('s3').generate_presigned_url(
  36. 'get_object',
  37. Params=dict(
  38. Bucket=settings.STORAGE_BUCKET,
  39. Key=key
  40. ),
  41. ExpiresIn=(expire_minutes * 60)
  42. ) if key else None
  43.  
  44.  
  45. class ImageManipulator(object):
  46. def resize(self, object_key, max_width):
  47. if not max_width:
  48. max_width = 640
  49.  
  50. if not os.path.exists('tmp'):
  51. os.makedirs('tmp')
  52.  
  53. temp_dir = os.path.abspath('tmp')
  54. obj_path = os.path.join(temp_dir, object_key)
  55.  
  56. obj = get_bucket_object(object_key)
  57. obj.download_file(obj_path)
  58.  
  59. in_img = None
  60. out_img = BytesIO()
  61.  
  62. try:
  63. in_img = Image.open(obj_path, 'r')
  64. except IOError:
  65. print("Cannot open file {}".format(object_key))
  66.  
  67. if in_img.width > max_width:
  68. in_img.thumbnail((in_img.height, max_width), Image.ANTIALIAS)
  69. in_img.save(out_img, in_img.format)
  70.  
  71. out_img.seek(0)
  72. out_img.name = object_key
  73. store_file_in_bucket(out_img, object_key)
  74.  
  75. os.remove(obj_path)
Add Comment
Please, Sign In to add comment