Python:写入文件失败没有错误 - 导致空文件

时间:2014-01-31 10:34:39

标签: python django

我正在使用Django来处理上传的文件并将其写入我项目中的某个位置。

处理文件上传的视图是:

def add_data(request):
    # If something was posted

    upload_form = DataImportUploadForm(request.POST, request.FILES) if request.method == 'POST' else DataImportUploadForm() 

    if request.method == 'POST':
        if upload_form.is_valid():
            upload_form.handle_uploaded_file()
            return HttpResponseRedirect(request, '/path/' ) 
        else:
            messages.error(request, ugettext(u"Could not import data"))

    return render_to_response('folder/add.html', {'upload_form': upload_form}, context_instance=RequestContext(request))

表格是:

class DataImportUploadForm(forms.Form):
    file = forms.FileField(label=_(u"File"), required=True)

    def __init__(self, *args, **kwargs):
        super(DataImportUploadForm, self).__init__(*args, **kwargs)
        self.max_upload_size = 1024*1024 #1 MB
        self.fileformat = None
        self.filename = None


    def clean_file(self):
        f = self.cleaned_data.get('file')
        if not f:
            raise forms.ValidationError(_(u"No file uploaded"))

        if f._size > self.max_upload_size:
            raise forms.ValidationError(_(u"Uploaded file is too large ( > 1MB )"))

        try:
            reader = csv.reader(f, csv.get_dialect('excel'))
            reader.next()
            self.fileformat = 'excel'
        except:
            reader = None

        if reader is None:
            try:
                dialect = csv.Sniffer().sniff(f.read(1024))
                f.seek(0)
                reader = csv.reader(f, dialect)
                self.fileformat = 'sniff'
            except:
                reader = None

        if reader is None:
            raise forms.ValidationError(_(u"Unknown data format"))

        self.filename = f._name

        return f

    def handle_uploaded_file(self):
        media_root = settings.MEDIA_ROOT
        file_location = media_root + 'CSV/'
        from core.helpers import ensure_dir
        ensure_dir(file_location)
        f = self.cleaned_data.get('file')
        dest = open(file_location + f._name, 'w+')
        logger.debug(dest)
        for chunk in f.chunks():
            logger.debug(chunk)
            dest.write(chunk)
        logger.debug(dest.closed)
        dest.seek(0)
        logger.debug(dest.read())
        dest.close()

上传文件时会发生什么(根据日志文件):

DEBUG 2014-01-31 12:04:46,034 POST URL: localhost.dev/path/?csrfmiddlewaretoken=683FesoraFTYLR7HHxfPuu3bb5xuzPYY&task=upload User: [me] Account: [useraccount]
DEBUG 2014-01-31 12:04:46,126 <open file u'/path/to/project/media/CSV/filename.csv', mode 'w+' at 0x54690c0>
DEBUG 2014-01-31 12:04:46,126 <FILE CONTENTS>
DEBUG 2014-01-31 12:04:46,126 False
DEBUG 2014-01-31 12:04:46,126 <FILE CONTENTS>
DEBUG 2014-01-31 12:04:46,817 GET URL: localhost.dev/path/of/next/view/ User: [me] Account: [useraccont]

我看到的是空文件。

起初我想,也许这是文件权限问题,但CSV文件夹有2777个烫发。以及媒体文件夹(包括媒体)以外的所有文件夹都具有正确的权限,允许访问文件夹。毕竟该死的脚本没有失败生成实际文件。

任何人都可以指出一些原因,为什么这个文件可能最终变空?

(project)alan@alan:/path/to/project/media/CSV$ ls -l
total 0
-rw-rw-rw- 1 alan alan 0 jaan  31 12:19 filename.csv

我使用的Django版本是1.4.2,python版本是2.7.5+。 Nginx + uwsgi&amp; virutalenv + virtualenvwrapper在ubuntu 13.10。

1 个答案:

答案 0 :(得分:1)

尝试刷新内部I / O缓冲区:

    # … your code …
    with open(file_location + f._name, 'w+') as dest:
        logger.debug(dest)
        for chunk in f.chunks():
            logger.debug(chunk)
            dest.write(chunk)
        dest.flush()

等待...在您的日志中显示:

    dest.seek(0)
    logger.debug(dest.read())

实际上在工作吗?然后内容已经写好了。

所以:

  • 因为拼写错误或其他错误而被写入错误的路径
  • 由于输入错误或其他错误,您没有打开正确的文件
  • 或您的文件被代码中的其他位置覆盖