首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Django视图不能通过使用熊猫[IOError]打开.csv文件

Django视图不能通过使用熊猫[IOError]打开.csv文件
EN

Stack Overflow用户
提问于 2015-06-11 09:48:13
回答 1查看 827关注 0票数 0

当我在IOError中打开.csv文件时,它说我在目录中没有这个文件,这是我的目录:

代码语言:javascript
运行
复制
/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

这是回溯

代码语言:javascript
运行
复制
    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就像:

代码语言:javascript
运行
复制
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)
    )

当我打开#标记时:

代码语言:javascript
运行
复制
# 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)

并让#签到:

代码语言:javascript
运行
复制
prostate_dataset=pd.read_csv(args[0])

它给了attribute error

代码语言:javascript
运行
复制
'tuple' object has no attribute 'method'

我该怎么办?提前感谢

更新6/11/2015:在views.py中添加完整的路径和完整的代码,我意识到,当我在views.py中删除list函数时,图形工作得很好,我认为list函数和showimage函数之间存在冲突。下面是属性错误跟踪:

代码语言:javascript
运行
复制
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'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-11 10:56:06

在views.py中添加完整的路径和完整的代码,我意识到,当我在views.py中删除list函数时,图形工作得很好,我认为列表函数和显示函数之间存在冲突

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30777247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档