【问题标题】:Django views can't open .csv file by using pandas [IOError]Django 视图无法使用 pandas 打开 .csv 文件 [IOError]
【发布时间】:2015-06-11 09:48:13
【问题描述】:

当我在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'

【问题讨论】:

  • 当前工作目录是否正确?您可能需要添加更完整的路径
  • 不是@EdChum,但是我写了一个更完整的路径和完整的views.py代码。很抱歉,我认为这会导致完全混乱。我觉得if request.method == 'POST'有问题

标签: python django file-io pandas django-views


【解决方案1】:

"在views.py中添加完整路径和完整代码,我实现了 某事,当我删除views.py 中的list 函数时,图表有效 很好,我认为列表函数和 显示图像函数"

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

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

【讨论】:

  • 在我更改函数名称后它可以无缝运行,非常感谢@bruno-desthuilliers :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
相关资源
最近更新 更多