Django - 获取PIL Image保存方法使用Amazon s3boto Storage [英] Django - Getting PIL Image save method to work with Amazon s3boto Storage
问题描述
为了在上传时调整图像的大小(使用PIL),我将覆盖我的文章模型的保存方式,如下所示:
In order to resize images upon upload (using PIL), I'm overriding the save method for my Article model like so:
def save(self):
super(Article, self).save()
if self.image:
size = (160, 160)
image = Image.open(self.image)
image.thumbnail(size, Image.ANTIALIAS)
image.save(self.image.path)
这在本地工作,但在生产中我收到错误:
NotImplementedError:此后端不支持绝对路径。
This works locally but in production I get an error: NotImplementedError: This backend doesn't support absolute paths.
我尝试用
image.save(self.image.url)
但是我得到一个IOError:
[Errno 2]没有这样的文件或目录:'< a href =https://my_bucket_name.s3.amazonaws.com/article/article_images/2.jpg> https://my_bucket_name.s3.amazonaws.com/article/article_images/2.jpg '
but then I get an IOError: [Errno 2] No such file or directory: 'https://my_bucket_name.s3.amazonaws.com/article/article_images/2.jpg'
这是图像的正确位置。如果我把这个地址放在浏览器中,图像就在那里。我尝试了许多其他的事情,但到目前为止,没有运气。
That is the correct location of the image though. If I put that address in the browser, the image is there. I tried a number of other things but so far, no luck.
推荐答案
你应该尝试避免保存到绝对路径;有一个文件存储API ,为您提取这些类型的操作。
You should try and avoid saving to absolute paths; there is a File Storage API which abstracts these types of operations for you.
查看 PIL文档,看来 save()
函数支持传递类似文件的对象而不是路径。
Looking at the PIL Documentation, it appears that the save()
function supports passing a file-like object instead of a path.
我不在一个环境,我可以测试这个代码,但我相信你需要做这样的事情,而不是最后一行:
I'm not in an environment where I can test this code, but I believe you would need to do something like this instead of your last line:
from django.core.files.storage import default_storage as storage
fh = storage.open(self.image.name, "w")
format = 'png' # You need to set the correct image format here
image.save(fh, format)
fh.close()
这篇关于Django - 获取PIL Image保存方法使用Amazon s3boto Storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!