我通过s3boto将Amazon S3用作存储后端.我有一个带有ImageField的Image模型.通过管理员上传图像后,该图像将成功上传到S3.我现在想要做的是使用Pillow创建缩略图后保存.我已经通过在其上调用show()方法验证了缩略图已创建,但是由于某种原因它没有被上传到S3.我认为我的保存方式可能是错误的-任何建议都将不胜感激.
I use Amazon S3 as my storage backend via s3boto. I have an Image model with an ImageField. When an image is uploaded via the admin, it is successfully uploaded to S3. What I am now trying to do is to create a thumbnail post-save using Pillow. I have verified that the thumbnail is being created by calling the show() method on it, but for some reason it is not being uploaded to S3. I think the way I am saving it may be wrong - any suggestions would be appreciated please.
tasks.py
from celery import shared_task from .models import Image import os from django.core.files.storage import default_storage as storage from PIL import Image as PillowImage @shared_task def create_thumbnails(pk): try: image = Image.objects.get(pk=pk) except Image.ObjectDoesNotExist: pass thumbnail_size = (450,200) filename, ext = os.path.splitext(image.image.name) try: fh = storage.open(image.image.name, 'r') im = PillowImage.open(fh) im.thumbnail(thumbnail_size) im.show() # TEST - This opens the resized image in Preview on my mac filename = filename +'_thumbnail' +ext new_file = storage.open(filename, 'w') im.save(new_file, "PNG") new_file.close() except IOError as error: print("cannot create thumbnail for ", filename, 'error ', error)堆栈
Django 1.85
django 1.85
python 2.7.10
python 2.7.10
推荐答案在经过数小时的痛苦的谷歌搜索后,终于可以正常工作了,这主要归功于此博客文章.
Finally got it working after a very painful few hours of googling, mostly thanks to this blog post.
tasks.py
from celery import shared_task import os from django.core.files.storage import default_storage as storage from django.conf import settings import mimetypes import cStringIO from PIL import Image as PillowImage import boto from .models import Image @shared_task def create_thumbnails(pk): try: image = Image.objects.get(pk=pk) except Image.ObjectDoesNotExist: pass try: thumbnail_size = (450,200) filename, ext = os.path.splitext(image.image.name) filename = filename +'_thumbnail' +ext existing_file = storage.open(image.image.name, 'r') im = PillowImage.open(existing_file) im = im.resize(thumbnail_size, PillowImage.ANTIALIAS) memory_file = cStringIO.StringIO() mime = mimetypes.guess_type(filename)[0] plain_ext = mime.split('/')[1] im.save(memory_file, plain_ext) conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) bucket = conn.get_bucket( 'yourbucketname', validate=False) k = bucket.new_key('media/' +filename) k.set_metadata('Content-Type', mime) k.set_contents_from_string(memory_file.getvalue()) k.set_acl("public-read") memory_file.close() except Exception as error: print("cannot create thumbnail for ", filename, 'error ', error)更多推荐
使用Boto将枕头文件保存到S3
发布评论