Django - Getting PIL Image save method to work with Amazon s3boto Storage

自古美人都是妖i 提交于 2019-12-07 02:53:20

问题


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)

This works locally but in production I get an error: NotImplementedError: This backend doesn't support absolute paths.

I tried replacing the image.save line with

image.save(self.image.url)

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.


回答1:


You should try and avoid saving to absolute paths; there is a File Storage API which abstracts these types of operations for you.

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()


来源:https://stackoverflow.com/questions/14680323/django-getting-pil-image-save-method-to-work-with-amazon-s3boto-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!