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

问题描述 投票:0回答:1

使用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
python django django-forms django-1.8 django-1.6
1个回答
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                                        
© www.soinside.com 2019 - 2024. All rights reserved.