comparison core/image_uploader.py @ 886:3d635fd53ef0

Merge with upstream.
author Brian Neal <bgneal@gmail.com>
date Tue, 03 Feb 2015 19:52:09 -0600
parents ee47122d6277
children 51a2051588f5
comparison
equal deleted inserted replaced
883:f12751259f66 886:3d635fd53ef0
1 """This module contains a function to upload an image file to a S3Bucket. 1 """This module contains a function to upload an image file to a S3Bucket.
2 2
3 The image can be resized and a thumbnail can be generated and uploaded as well. 3 The image can be resized and a thumbnail can be generated and uploaded as well.
4 4
5 """ 5 """
6 from base64 import b64encode
6 import logging 7 import logging
7 from io import BytesIO 8 from io import BytesIO
8 import os.path 9 import os.path
9 import tempfile 10 import tempfile
10 import uuid 11 import uuid
14 from core.functions import temp_open 15 from core.functions import temp_open
15 from core.image import orient_image 16 from core.image import orient_image
16 17
17 18
18 logger = logging.getLogger(__name__) 19 logger = logging.getLogger(__name__)
20
21
22 def make_key():
23 """Generate a random key suitable for a filename"""
24 return b64encode(uuid.uuid4().bytes, '-_').rstrip('=')
19 25
20 26
21 def upload(fp, bucket, metadata=None, new_size=None, thumb_size=None): 27 def upload(fp, bucket, metadata=None, new_size=None, thumb_size=None):
22 """Upload an image file to a given S3Bucket. 28 """Upload an image file to a given S3Bucket.
23 29
52 # problematic because the file is often an in-memory file if it is under 58 # problematic because the file is often an in-memory file if it is under
53 # a certain size. This complicates matters and many of the operations we try 59 # a certain size. This complicates matters and many of the operations we try
54 # to perform on it fail if this is the case. To get around these issues, 60 # to perform on it fail if this is the case. To get around these issues,
55 # we make a copy of the file on the file system and operate on the copy. 61 # we make a copy of the file on the file system and operate on the copy.
56 # First generate a unique name and temporary file path. 62 # First generate a unique name and temporary file path.
57 unique_key = uuid.uuid4().hex 63 unique_key = make_key()
58 ext = os.path.splitext(fp.name)[1] 64 ext = os.path.splitext(fp.name)[1]
59 temp_name = os.path.join(tempfile.gettempdir(), unique_key + ext) 65 temp_name = os.path.join(tempfile.gettempdir(), unique_key + ext)
60 66
61 # Write the UploadedFile to a temporary file on disk 67 # Write the UploadedFile to a temporary file on disk
62 with temp_open(temp_name, 'wb') as temp_file: 68 with temp_open(temp_name, 'wb') as temp_file: