12345678910111213141516171819202122232425262728293031323334353637383940 |
- def upload_file_to_s3(file_key, filename, key, do_gzip=False,
- do_expires=False, verbosity=0):
- """Details about params:
- * file_key is the relative path from media, e.g. media/folder/file.png
- * filename is the full path to the file, e.g.
- /var/www/site/media/folder/file.png
- """
- headers = {}
- content_type = guess_mimetype(filename)
- file_obj = open(filename, 'rb')
- if content_type:
- headers['Content-Type'] = content_type
- file_size = os.fstat(file_obj.fileno()).st_size
- filedata = file_obj.read()
- if do_gzip:
- # Gzipping only if file is large enough (>1K is recommended)
- # and only if file is a common text type (not a binary file)
- if file_size > 1024 and content_type in GZIP_CONTENT_TYPES:
- filedata = compress_string(filedata)
- headers['Content-Encoding'] = 'gzip'
- gzip_file_size = len(filedata)
- if verbosity > 1:
- print ("\tgzipped: %dk to %dk" % \
- (file_size / 1024, gzip_file_size / 1024))
- file_size = gzip_file_size
- headers['Content-Length'] = str(file_size)
- if do_expires:
- # HTTP/1.0
- headers['Expires'] = '%s GMT' % (email.Utils.formatdate(
- time.mktime((datetime.datetime.now() +
- datetime.timedelta(days=365 * 2)).timetuple())))
- # HTTP/1.1
- headers['Cache-Control'] = 'max-age %d' % (3600 * 24 * 365 * 2)
- try:
- key.name = file_key
- key.set_contents_from_string(filedata, headers, replace=True)
- key.set_acl('public-read')
- finally:
- file_obj.close()
|