尝试打开上传文件时,“关闭文件上的I / O操作”错误django 1.8

时间:2017-12-01 13:15:24

标签: python django django-forms django-1.8 django-1.6

使用Django1.8时无法打开上传的文件,我遇到错误“ ValueError:关闭文件的I / O操作”。但是这在Django 1.6中运行得很好:

Django1.8
>>>type(in_file)
<class 'django.core.files.uploadedfile.TemporaryUploadedFile'>
>>>in_file.closed
True

Django1.6
>>>type(in_file)
<class 'django.core.files.uploadedfile.TemporaryUploadedFile'>
>>>in_file.closed
False

def save_to_file(in_file, dest_file, type='w'):
    try:
        with open(dest_file, type) as out_file:
            for line in in_file:
                out_file.write(line)
    except Exception as e:
        print "Error::--{}".format(e)
>>>save_to_file(in_file, '/Work/YYY.FLAT')
Error::--I/O operation on closed file

1 个答案:

答案 0 :(得分:0)

在openstack论坛上报告了类似的bug以及修复。请参阅帖子here并修正here。您的代码可能如下所示,

def mark_inmemory_file_close(myfile):
    if myfile:
        # There is a bug in Django 1.7, which causes InMemoryUploadedFile to close automatically. The new thread
        # always has a closed file to read.
        # Fix - https://git.openstack.org/cgit/openstack/horizon/commit/?id=78e9a997e4c6faf393d3bdaa3a043f1796aaa1bd
        if isinstance(myfile, TemporaryUploadedFile):
            # Hack to fool Django 7 and above, so we can keep file open in the new thread.
            myfile.file.close_called = True
        if isinstance(myfile, InMemoryUploadedFile):
            # Clone a new file for InMemeoryUploadedFile.
            # Because the old one will be closed by Django.
            myfile = SimpleUploadedFile(myfile.name,
                                              myfile.read(),
                                              myfile.content_type)
        return myfile
    return None