如何修复以下 Django 错误:“类型:IOError” “值:[Errno 13]权限被拒绝”

发布于 2024-09-30 19:33:41 字数 3304 浏览 5 评论 0原文

我正在遵循 Django 教程,在该教程中,一旦图像保存在管理中,您就需要构建一些图像缩略图。我还使用 Python 的 tempfile 模块来保存临时文件名。

但是我不断遇到以下错误:

"Type: IOError" "Value: [Errno 13] Permission denied: 'c:\\docume~1\\myname\\locals~1\\temp\\somefilename'"

这是我正在使用的代码

Settings

MEDIA_ROOT = '/home/myname/projectname/media/'
MEDIA_URL = 'http://127.0.0.1:8000/media/'enter code here

models.py

from string import join
import os
from PIL import Image as PImage
from settings import MEDIA_ROOT
from os.path import join as pjoin
from tempfile import *
from string import join
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from django.core.files import File

class Image(models.Model):
    title = models.CharField(max_length=60, blank=True, null=True)
    image = models.FileField(upload_to="images/")
    thumbnail = models.ImageField(upload_to="images/", blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True)
    albums = models.ManyToManyField(Album, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    rating = models.IntegerField(default=50)
    width = models.IntegerField(blank=True, null=True)
    height = models.IntegerField(blank=True, null=True)
    user = models.ForeignKey(User, null=True, blank=True)
    thumbnail2 = models.ImageField(upload_to="images/", blank=True, null=True)

def save(self, *args, **kwargs):
    #Save image dimensions
    super(Image, self).save(*args, **kwargs)
    im = PImage.open(pjoin(MEDIA_ROOT, self.image.name))
    self.width, self.height = im.size

    # large thumbnail
    fn, ext = os.path.splitext(self.image.name)
    im.thumbnail((128,128), PImage.ANTIALIAS)
    thumb_fn = fn + "-thumb2" + ext
    tf2 = NamedTemporaryFile()
    im.save(tf2.name, "JPEG")
    self.thumbnail2.save(thumb_fn, File(open(tf2.name)), save=False)
    tf2.close()

    # small thumbnail
    im.thumbnail((40,40), PImage.ANTIALIAS)
    thumb_fn = fn + "-thumb" + ext
    tf = NamedTemporaryFile()
    im.save(tf.name, "JPEG")
    self.thumbnail.save(thumb_fn, File(open(tf.name)), save=False)
    tf.close()

    super(Image, self).save(*args, **kwargs)

def size(self):
    """Image size."""
    return "%s x %s" % (self.width, self.height)

def __unicode__(self):
    return self.image.name

def tags_(self):
    lst = [x[1] for x in self.tags.values_list()]
    return str(join(lst, ', '))

def albums_(self):
    lst = [x[1] for x in self.albums.values_list()]
    return str(join(lst, ', '))

def thumbnail_(self):
    return """<a href="/media/%s"><img border="0" alt="" src="/media/%s" /></a>""" % (
                                                        (self.image.name, self.thumbnail.name))
thumbnail.allow_tags = Trueenter code here

ADMIN

class ImageAdmin(admin.ModelAdmin):
    # search_fields = ["title"]
    list_display = ["__unicode__", "title", "user", "rating", "size",  "tags_","albums_",
    "thumbnail", "created"]
list_filter = ["tags", "albums", "user"]

def save_model(self, request, obj, form, change):
    obj.user = request.user
    obj.save()

我知道在 Django 中使用图像缩略图有更有效的方法,但是我想知道为什么在缩略图时我不断收到此权限错误以这种方式使用。

非常感谢所有帮助。谢谢。

I am following a Django Tutorial where you are required to construct some image thumbnails once an image is saved in admin. I am also using Python's tempfile module to save a temporary file name.

However I keep running into the following error:

"Type: IOError" "Value: [Errno 13] Permission denied: 'c:\\docume~1\\myname\\locals~1\\temp\\somefilename'"

Here is the code I am using

Settings

MEDIA_ROOT = '/home/myname/projectname/media/'
MEDIA_URL = 'http://127.0.0.1:8000/media/'enter code here

models.py

from string import join
import os
from PIL import Image as PImage
from settings import MEDIA_ROOT
from os.path import join as pjoin
from tempfile import *
from string import join
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
from django.core.files import File

class Image(models.Model):
    title = models.CharField(max_length=60, blank=True, null=True)
    image = models.FileField(upload_to="images/")
    thumbnail = models.ImageField(upload_to="images/", blank=True, null=True)
    tags = models.ManyToManyField(Tag, blank=True)
    albums = models.ManyToManyField(Album, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    rating = models.IntegerField(default=50)
    width = models.IntegerField(blank=True, null=True)
    height = models.IntegerField(blank=True, null=True)
    user = models.ForeignKey(User, null=True, blank=True)
    thumbnail2 = models.ImageField(upload_to="images/", blank=True, null=True)

def save(self, *args, **kwargs):
    #Save image dimensions
    super(Image, self).save(*args, **kwargs)
    im = PImage.open(pjoin(MEDIA_ROOT, self.image.name))
    self.width, self.height = im.size

    # large thumbnail
    fn, ext = os.path.splitext(self.image.name)
    im.thumbnail((128,128), PImage.ANTIALIAS)
    thumb_fn = fn + "-thumb2" + ext
    tf2 = NamedTemporaryFile()
    im.save(tf2.name, "JPEG")
    self.thumbnail2.save(thumb_fn, File(open(tf2.name)), save=False)
    tf2.close()

    # small thumbnail
    im.thumbnail((40,40), PImage.ANTIALIAS)
    thumb_fn = fn + "-thumb" + ext
    tf = NamedTemporaryFile()
    im.save(tf.name, "JPEG")
    self.thumbnail.save(thumb_fn, File(open(tf.name)), save=False)
    tf.close()

    super(Image, self).save(*args, **kwargs)

def size(self):
    """Image size."""
    return "%s x %s" % (self.width, self.height)

def __unicode__(self):
    return self.image.name

def tags_(self):
    lst = [x[1] for x in self.tags.values_list()]
    return str(join(lst, ', '))

def albums_(self):
    lst = [x[1] for x in self.albums.values_list()]
    return str(join(lst, ', '))

def thumbnail_(self):
    return """<a href="/media/%s"><img border="0" alt="" src="/media/%s" /></a>""" % (
                                                        (self.image.name, self.thumbnail.name))
thumbnail.allow_tags = Trueenter code here

ADMIN

class ImageAdmin(admin.ModelAdmin):
    # search_fields = ["title"]
    list_display = ["__unicode__", "title", "user", "rating", "size",  "tags_","albums_",
    "thumbnail", "created"]
list_filter = ["tags", "albums", "user"]

def save_model(self, request, obj, form, change):
    obj.user = request.user
    obj.save()

I know there are much more effective ways of using image thumbnails in Django however I would like to know why I keep getting this Permission error when thumbnails are used in this manner.

All help is greatly appreciated. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

云巢 2024-10-07 19:33:41

我认为这取决于 Windows 上 NamedTemporaryFile 的行为。来自文档

该函数的运行方式与
TemporaryFile() 确实如此,除了
文件保证有一个可见的
文件系统中的名称(在 Unix 上,
目录条目未取消链接)。那
可以从名称中检索名称
文件对象的成员。 是否
name 可用于打开文件 a
第二次,而命名的临时
文件仍然打开,各不相同
平台(在Unix上可以这样使用;
它不能在 Windows NT 或更高版本上
)。

(强调我的)

行中:

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

save 可能会尝试打开该文件,以便可以写入该文件。

PIL 文档 中,您可以传递 save 文件对象而不是文件名,因此将上面的内容替换为

im.save(tf2, "JPEG")

可能会有所帮助。

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.

凉宸 2024-10-07 19:33:41

我很遗憾,但 mikej 的答案根本不是解决方案,因为 PIL 支持这两种语法示例。可能,我从某处复制了同一个软件,它在我的 linux 机器上完美运行,但在 Windows 7 上不行。原因不在于图像保存命令,而在于以下命令。命令 ...

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

... 导致权限被拒绝错误,因为文件仍然打开并且无法在 Windows 上至少打开两次。可以通过以下方式模拟相同的错误。

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

正确的解决方法是

  1. 创建一个关闭时不会删除的临时文件
  2. 保存并关闭缩略图
  3. 手动删除临时文件

无论您如何保存缩略图,这都有效。

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文