How do you fix the following Django Error: “Type: IOError” “Value: [Errno 13] Permission denied”

烂漫一生 提交于 2019-12-01 08:38:06

I think this is down to the behavior of NamedTemporaryFile on Windows. From the documentation:

This function operates exactly as TemporaryFile() does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name member of the file object. Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

(emphasis mine)

in the line:

im.save(tf2.name, "JPEG")

save presumably tries to open the file so that it can write to it.

From the PIL docs you can pass save a file object instead of a filename so replacing the above with

im.save(tf2, "JPEG")

may help.

I regret but mikej's answer is not a solution at all as PIL supports both syntax examples. Probably, I copied the same piece of software from somewhere, and it works perfectly on my linux machines but not on windows 7. The reason is not in the image save command but rather in the following one. The command ...

self.thumbnail.save(thumb_fn, File(open(tf.name)), save=False)

... causes the permission denied error because the file is still open and cannot be opened twice at least on windows. The same error can be simulated by

copyfile(tf2.name,"some-new-filepath")

A proper workaround is

  1. Create a temporary file that is not deleted when closed
  2. Save and close the thumbnail
  3. Remove the temporary file manually

This works no matter how you save the thumbnail.

tf = NamedTemporaryFile(delete=False)
im.save(tf.name, "PNG")
#im.save(tf, "PNG")
tf.close()
copyfile(tf.name,"some-new-filepath")
os.remove(tf.name)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!