gpt4 book ai didi

python - Django:上传的文件已锁定。无法重命名

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:24 24 4
gpt4 key购买 nike

在模型的保存方法中上传文件后,我正在尝试重命名文件。我将文件重命名为文件主键和文件标题的组合。

我在首次上传文件时、上传新文件时以及文件或文件标题没有更改时运行。

但是,当文件的标题被更改,并且系统尝试将旧文件重命名为新路径时,我收到以下错误:

WindowsError at /admin/main/file/1/
(32, 'The process cannot access the file because it is being used by another process')

我真的不知道如何解决这个问题。我试过将文件复制到新路径。这行得通,但我不知道我是否可以删除旧版本。

缩短模型:

class File(models.Model):
nzb = models.FileField(upload_to='files/')
name = models.CharField(max_length=256)
name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False)

def save(self):
# Create the name slug.
self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower()
self.name_slug = re.sub('[-]+', '-', self.name_slug)

# Need the primary key for naming the file.
super(File, self).save()

# Create the system paths we need.
orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb}
renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug}

# Rename the file.
if orignal_nzb not in renamed_nzb:
if os.path.isfile(renamed_nzb):
os.remove(renamed_nzb)

# Fails when name is updated.
os.rename(orignal_nzb, renamed_nzb)

self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug}

super(File, self).save()

我想问题是,有谁知道当上传的文件没有被重新上传时如何重命名上传的文件?这是唯一一次它似乎被锁定/正在使用。


更新:

Tyler 的方法很有效,除非上传新文件时主键不可用并且他下面的技术会引发错误。

if not instance.pk:
instance.save()

错误:

maximum recursion depth exceeded while calling a Python object

有什么办法可以抓到主键吗?

最佳答案

我认为您应该更仔细地查看 upload_to 字段。这可能比在保存期间搞乱重命名更简单。

http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield

This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:

关于python - Django:上传的文件已锁定。无法重命名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/637160/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com