【问题标题】:WindowsError: [Error 32] when trying to delete FileField in DjangoWindowsError:尝试在 Django 中删除 FileField 时 [错误 32]
【发布时间】:2018-07-05 19:25:16
【问题描述】:

我正在编写一个 django-nose 测试来测试文档上传功能。在测试中,我使用来自django.core.files.uploadedfileSimpleUploadedFile() 模拟新文档。问题是与文档实例关联的文件无法在 Windows 上删除(Linux 上的测试通过)。我收到以下错误:

in auto_delete_file_on_delete()->
os.remove(instance.document.path)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: 

这是我的测试:

def test_delete_doc(self):
    self.client.login(username='xx', password='xx')
    dir_path = os.getcwd()
    manager_user = User.objects.get(username='xx')

    file_name = "test_document"
    file_path = os.path.join(dir_path, file_name)
    new_file = open(file_path, "w")
    new_file.write("Some file content")
    new_file.close()
    new_file = open(os.path.join(dir_path, file_name), "rb")
    new_doc = SimpleUploadedFile(name=file_name, content=new_file.read())
    new_file.close()
    self.client.post(reverse('view_upload'),
                     {'employee_id': manager_user.profile.employee.empId, 'document': new_doc})
    self.assertEqual(len(Document.objects.all()), 1)
    self.client.post(reverse('delete'), {'file_id': Document.objects.all().first().pk})
    self.assertEqual(len(Document.objects.all()), 0)

我的看法(reverse('delete')delete_document()):

def delete_document(request):
    instance = Document.objects.get(doc_id=request.POST['file_id'])
    instance.delete()
    return redirect('view_upload')

以及附加到实例移除的信号:

@receiver(models.signals.post_delete, sender=Document)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    if instance.document:
        if os.path.isfile(instance.document.path):
            os.remove(instance.document.path)

有人知道为什么会这样吗?

我已经尝试过(遇到同样的错误):

  1. 使用with 打开/关闭文件。
  2. 使用os.open()/os.read()/os.close()处理文件。
  3. 删除 SimpleUploadedFile() 并简单地使用 new_doc = open() 打开文件并将其传递给 POST 请求。

谢谢!

【问题讨论】:

  • 您是否尝试在关闭文件后稍微休眠(可能 5 秒)?因为如果我记得正确的 python 方法 close() 并不能保证文件真的关闭和解锁。
  • @teror4uks 不起作用,同样的错误

标签: django windows python-2.7 django-signals django-nose


【解决方案1】:

SimpleUploadedFile 在内存中,所以没关系,您发布的代码中没有什么太糟糕的地方。 view_uploadDocument.save() 或其他将文件写入磁盘的东西是否会关闭它?

它适用于 Linux,因为您可以删除打开的文件。

【讨论】:

  • 那么文件是在test_delete_doc 中打开的,我在view_upload 之后立即关闭它,所以我认为它不应该在视图中的某个地方关闭。
猜你喜欢
  • 1970-01-01
  • 2013-04-09
  • 2019-07-07
  • 1970-01-01
  • 1970-01-01
  • 2018-12-14
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多