2016-02-29 39 views
1

嘗試通過CSV下載導出的數據時,終端返回錯誤。它不是一個簡單的x.read()與x.open()相似的堆棧問題shown here,但相當複雜,因爲它通過Pyramid和Pyramid的Response方法寫入並保存到csv文件。ValueError:金字塔中關閉文件的I/O操作

我有點困惑,爲什麼發生這種情況,並可以使用一些指導找到bug。我感謝指導和建議。

的Python 2.7,金字塔


查看代碼:

def export_results(request): 
    response = Response(content_type='application/csv') 
    results = api.retrieve_assessment_results() #list retrieval of all results from db e.g. [<class(element, element)>, <class2(element, element)> ...] 

    with NamedTemporaryFile(prefix='Export_%s' % datetime.now(), 
     suffix='.csv', delete=True) as f: 

     fileWriter = csv.writer(f, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL) 

     for a in results: 
      print(a) 
      fileWriter.writerow(['a.owner', 'a.assessment']) 

     response.app_iter = f 
     response.headers['content_disposition'] = ('attachment; filename=Export.csv') 

     return response 

@view_config(route_name='analyst_view', renderer='templates/analyst_page.jinja2', request_method='GET', permission='read') 
def analyst_view(request): 
    #some other code 
    export = export_results(request) 

    return {#other code, 'export': export} 

終端錯誤:

"/usr/local/lib/python2.7/site-packages/pyramid-1.5.7-py2.7.egg/pyramid/renderers.py", line 447, in render 
    result = renderer(value, system_values) 
    File "/usr/local/lib/python2.7/site-packages/pyramid_jinja2-2.5-py2.7.egg/pyramid_jinja2/__init__.py", line 265, in __call__ 
    return template.render(system) 
    File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render 
    return self.environment.handle_exception(exc_info, True) 
    File "/usr/local/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception 
    reraise(exc_type, exc_value, tb) 
    File "/Users/ack/code/venv/WEB/web/templates/analyst_page.jinja2", line 76, in top-level template code 
    <div class="thumbnail"> <a href="{{export}}"><img src="{{request.static_url('web:static/img/book_bw.png')}}" width="2000" class="cards"/></a> 
    File "build/bdist.macosx-10.10-x86_64/egg/webob/response.py", line 230, in __str__ 
    self.body 
    File "build/bdist.macosx-10.10-x86_64/egg/webob/response.py", line 345, in _body__get 
    body = b''.join(app_iter) 
ValueError: I/O operation on closed file 

回答

2

通過返回從with塊的響應,你正在縮小NamedTemporaryFile前它被返回。您不想寫入文件,而是寫入stream

我使用類似Python3/Pyramid/SQLAlchemy下面的代碼,這對我很有用。不要有蟒蛇2安裝,所以沒有測試過蟒蛇2

import StringIO 

f = StringIO.StringIO() 

fileWriter = csv.writer(f, delimiter=',',quotechar='|',quoting=csv.QUOTE_MINIMAL) 

for a in results: 
    print(a) 
    fileWriter.writerow(['a.owner', 'a.assessment']) 

#rewind file 
f.seek(0) 
response = Response(
    request=request, 
    content_disposition='attachment; filename="filename.csv"') 
) 
response.app_iter = f 

return response 
+0

我得到一個錯誤:'文件「/Users/ack/code/venv/WEB/web/views/default.py」,行104 ,在analyst_view export = export_results(request) 文件「/Users/ack/code/venv/WEB/nweb/views/default.py」,第83行,在export_results中 fileWriter.writerow([a.owner,a。評估]) TypeError:unicode參數預計,得到'str'' – thesayhey

+1

我現在看到你在Python 2.7,所以語法也有​​點不同。如果這不起作用,請檢查[此問題](http://stackoverflow.com/questions/13120127/how-can-i-use-io-stringio-with-the-csv-module)。也許想到升級到python 3;) –

+0

出於某種原因,這導致導出按鈕404未找到錯誤:404找不到 資源找不到。 /users/200 OKContent-Type:application/csvcontent_disposition:attachment; filename = Export.csvContent-Length:41547 | ',AND MORE code ....'所以它的打印是正確的,但是當按鈕被擊中時不會作爲文件導出。 – thesayhey

相關問題