我(最终)从Django 1.8升级到Django 1.10,虽然有一些明显的挑战,唯一的困难是我的图像上传到S3。升级Django时,我也被迫升级Boto& PIL。
虽然原始图像仍然可以正确上传到请求的存储桶(原件),但是创建拇指并将其保存到另一个存储桶的保存功能不再有效。
这是我的代码在Django / Boto / PIL升级之前正常工作:
class Photo(models.Model):
...
def save(self, *args, **kwargs):
super(Photo, self).save(*args, **kwargs)
self.create_avatar_thumb()
def create_avatar_thumb(self):
import os
from PIL import Image
from django.core.files.storage import default_storage as storage
if not self.filename:
return ""
file_path = self.filename.name
filename_base, filename_ext = os.path.splitext(file_path)
original_file_path = "%s%s" % (filename_base, filename_ext)
xm_file_path = original_file_path.replace('originals/', 'xm/')
if storage.exists(xm_file_path):
return "exists"
# resize the original image to xs
f = storage.open(file_path, 'r')
image = Image.open(f)
print image # example 1
xm_size = 40, 40
image.thumbnail(xm_size, Image.ANTIALIAS)
f_thumb = storage.open(xm_file_path, "w")
print f_thumb # example 2
image.save(f_thumb, quality=100)
f_thumb.close()
我的测试:
运行此脚本时没有错误。
两个观察结果:当我运行print
时, #example 1 会打印两次而 #example 2 上的print
为空< / p>
答案 0 :(得分:1)
我在使用s3的Pillow .save()
方法时遇到问题所以我在保存之前经历了一个StringIO。
from django.core.files.storage import default_storage as storage
from cStringIO import StringIO #for python2, you'd use "from io..." in python3
# let's say we have a PIL image called 'Image'
sfile = StringIO()
Image.save(sfile, format="png") # save a png to the StringIO
with storage.open('somepath/somefile.png', 'w+') as f:
f.write(sfile.getvalue())
我在Django 1.9上。我不知道为什么这会破坏您的升级,但这对我有用。
答案 1 :(得分:1)
Jeremy S.答案对我有用,但我需要使用BytesIO(): 从io导入BytesIO。这是在AWS上使用带有python3和s3Boto3存储的django 1.11。