将文件传递给函数进行解析

时间:2015-03-17 01:59:07

标签: python django

我有一个上传表单,它接受一个文件并将其发送到一个要解析的函数。它是一个CSV文件,我使用DataField类型来存储它。

views.py

def upload(request):
    # Handle file upload
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = CSV(file=request.FILES['csvfile'])
            newdoc.save()

            # Send file to parser
            import fanduel.load_data
            fanduel.load_data.parse(newdoc.file, request.user)

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('app.views.upload'))
    else:
        form = UploadForm()  # A empty, unbound form

load_data.py

def parse(file, username):
    import csv
    dataReader = csv.reader(open(file), delimiter=',', quotechar='"')

forms.py

# In forms.py...
from django import forms

class UploadForm(forms.Form):
    csvfile = forms.FileField(
        label='Select a CSV file',
    )

models.py

class CSV(models.Model):
    file = models.FileField(upload_to='csv/')

回溯:

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/app/

Django Version: 1.7.6
Python Version: 3.4.2
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'import_export',
 'app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "C:\Users\Wilson\AppData\Roaming\Python\Python34\site-packages\django\core\handlers\base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Wilson\PycharmProjects\bankroll2\app\views.py" in upload
  20.             app.load_data.parse(newdoc.file, request.user)
File "C:\Users\Wilson\PycharmProjects\bankroll2\app\load_data.py" in parse
  13.     dataReader = csv.reader(open(file), delimiter=',', quotechar='"')

Exception Type: TypeError at /app/
Exception Value: invalid file: <FieldFile: csv/app_entry_history_20150316_w62ruKt.csv>

我不知道如何让它作为正确的文件类型传递它。如果我手动将文件路径输入到load_data.py中,它可以正常工作,因此它与传入的方式有关。

1 个答案:

答案 0 :(得分:0)

认为你的问题是你试图打开错误的文件名。当文件上传到Web服务器时,它要么存储在内存中,要么写入临时位置 - Django也会这样做(https://docs.djangoproject.com/en/1.7/topics/http/file-uploads/#where-uploaded-data-is-stored)。

因此request.FILES['csv']中的值是临时文件的位置。你想要的是存储在表单中的文件。您需要粘贴表单和模型,但我猜测以下内容可能会起作用,所以不要使用此

newdoc = CSV(file=request.FILES['csvfile'])

你需要

newdoc = CSV(file=form.cleaned_data['csvfile'])