Django 视图无法使用 pandas [IOError] 打开 .csv 文件

Django views can't open .csv file by using pandas [IOError]

当我打开 views.py 中的 .csv 文件时出现 IOError,它说我的目录中没有该文件,这是我的目录:

/survat         #theproject
    /survatapp  #theapp
        /modules
            __init__.py
            survat_core.py
        __init__.py
        views.py
        forms.py
        models.py
        prostate1.csv
    __init__.py
    settings.py
    urls.py
    wsgi.py        
/database
        sqlite.db
/media
/static
    /bootstrap

这是回溯

    Environment:


Request Method: GET
Request URL: http://localhost:8000/graph.png

Django Version: 1.4.1
Python Version: 2.7.9
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'survat.survatapp')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Milexjaro\Dropbox\Thesis2\survat\survatapp\views.py" in showimage
  129.     printaalen('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx')
File "C:\Users\Milexjaro\Dropbox\Thesis2\survat\survatapp\views.py" in printaalen
  105.         prostate_dataset=pd.read_csv(args[0])
File "C:\Python27\lib\site-packages\pandas\io\parsers.py" in parser_f
  465.         return _read(filepath_or_buffer, kwds)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py" in _read
  241.     parser = TextFileReader(filepath_or_buffer, **kwds)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py" in __init__
  557.         self._make_engine(self.engine)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py" in _make_engine
  694.             self._engine = CParserWrapper(self.f, **self.options)
File "C:\Python27\lib\site-packages\pandas\io\parsers.py" in __init__
  1061.         self._reader = _parser.TextReader(src, **kwds)

Exception Type: IOError at /graph.png
Exception Value: File prostate1.csv does not exist

我的 views.py 就像:

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from survat.survatapp.models import Document
from survat.survatapp.forms import DocumentForm
from django.http import HttpResponse
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from lifelines import CoxPHFitter,AalenAdditiveFitter
from django.http import HttpResponse
from matplotlib import pylab
from pylab import *
import PIL, PIL.Image, StringIO
from survat.survatapp.modules.survat_core import printall

def showimage(request):    
    def printaalen(*args):
        # module_dir = os.path.dirname(__file__)  # get current directory
        # file_path = os.path.join(module_dir, 'prostate1.csv')
        # prostate_dataset=pd.read_csv(file_path)
        prostate_dataset=pd.read_csv(args[0]) #<-- This is the issue
        prostate_dataset=prostate_dataset[list(args[1:])]
        pdplot=prostate_dataset[list(args[3:])]
        for x in prostate_dataset:
            if (prostate_dataset[x].dtype=="object"):
                cat=pd.Series(list(prostate_dataset[x]))
                for y in pd.unique(cat):
                    prostate_dataset[x+'.'+y]=pd.get_dummies(cat)[y]
                prostate_dataset.drop(x, axis=1, inplace=True)

            else:
                pass

        aaf=AalenAdditiveFitter(fit_intercept=False)
        aaf.fit(prostate_dataset,args[1],event_col=args[2])
        aalenListPlot=list(prostate_dataset.columns.values)[2:]
        aalenPlotTemp=[]
        for x in aalenListPlot:
            aalenPlotTemp.append(aaf.plot( columns=[ x ], color='red' ))

        return aaf.plot( columns=[ 'age','hg' ], color='red' )

    printaalen('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx')

    xlabel('X Bar')
    ylabel('Y Bar')
    title('Significance of dataset')
    grid(True)

    # Store image in a string buffer
    buffer = StringIO.StringIO()
    canvas = pylab.get_current_fig_manager().canvas
    canvas.draw()
    pilImage = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
    pilImage.save(buffer, "PNG")
    pylab.close()

    # Send buffer in a http response the the browser with the mime type image/png set
    return HttpResponse(buffer.getvalue(), mimetype="image/png")

def list(request):
    # Handle file upload
    if request.method == 'POST':

        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Document(docfile = request.FILES['docfile'])
            newdoc.save()

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

    # Load documents for the list page
    documents = Document.objects.all()

    def delete_matrix():
        documents = Document.objects.all()
        for document in documents:
            document.delete()

    ae=printall('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx')

    # Render list page with the documents and the form
    return render_to_response(
        'survatapp/list.html',
        {'documents': documents, 'form': form, 'ae':ae},
        context_instance=RequestContext(request)
    )

当我打开 # 登录时:

# module_dir = os.path.dirname(__file__)  # get current directory
# file_path = os.path.join(module_dir, 'prostate1.csv')
# prostate_dataset=pd.read_csv(file_path)

并给#签到:

prostate_dataset=pd.read_csv(args[0])

它给出 attribute error:

'tuple' object has no attribute 'method'

我该怎么办?提前致谢

2015 年 6 月 11 日更新:在 views.py 中添加完整路径和完整代码,我意识到,当我在 views.py 中删除 list 函数时,图形工作正常,我认为 list 函数和 showimage 函数之间存在冲突。这是属性错误回溯:

Environment:


Request Method: GET
Request URL: http://localhost:8000/graph.png

Django Version: 1.4.1
Python Version: 2.7.9
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'survat.survatapp')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Milexjaro\Dropbox\Thesis2\survat\survatapp\views.py" in showimage
  129.     printaalen('prostate1.csv','dtime','status1','age','hg','sz','sg','pf','rx')
File "C:\Users\Milexjaro\Dropbox\Thesis2\survat\survatapp\views.py" in printaalen
  106.         prostate_dataset=prostate_dataset[list(args[1:])]
File "C:\Users\Milexjaro\Dropbox\Thesis2\survat\survatapp\views.py" in list
  24.     if request.method == 'POST':

Exception Type: AttributeError at /graph.png
Exception Value: 'tuple' object has no attribute 'method'

"Adding complete path and complete code in views.py, and I realized something, when I delete list function in views.py the graph worked just fine, I think there is a clash between list function and showimage function"

是的,的确如此。将视图函数命名为 list 会在整个模块的命名空间中隐藏内置类型 list,因此在 printaalen() 中,当您尝试使用内置列表类型时,您会调用视图函数。

TL;DR : 不要隐藏内置名称。