При попытке загрузить экспортированные данные через CSV терминал возвращается с ошибкой. Это непростая проблема x.read() по сравнению с x.open() как shown here по аналогичному вопросу о стеках, но довольно сложная, так как она записывает и сохраняет в файл csv с помощью метода Response Pyramid и Pyramid.ValueError: операция ввода-вывода в закрытом файле в Pyramid
Я немного смущен, почему это происходит и может использовать некоторые рекомендации по поиску ошибки. Я ценю рекомендации и предложения.
Python 2.7, Пирамида
View Code:
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}
Terminal Error:
"/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
Я получаю сообщение об ошибке: 'File«/Users/ack/code/venv/WEB/web/views/default.py», строка 104 , в analytic_view export = export_results (запрос) Файл «/Users/ack/code/venv/WEB/nweb/views/default.py», строка 83, в export_results fileWriter.writerow ([a.owner, a. оценка]) ТипError: аргумент unicode ожидается, получил 'str'' – thesayhey
Теперь я вижу, что вы находитесь на Python 2.7, поэтому синтаксис немного отличается. Если это не сработает, проверьте [этот вопрос] (http://stackoverflow.com/questions/13120127/how-can-i-use-io-stringio-with-the-csv-module). И, возможно, подумайте об обновлении до python 3;) –
По какой-то причине это вызывает кнопку экспорта ошибки 404 Not Found: '404 Not Found Ресурс не найден. /users/200 OKContent-Type: application/csvcontent_disposition: attachment; filename = Export.csvContent-Length: 41547 | ', AND MORE code .... 'поэтому он печатает правильно, но не экспортирует его в файл, когда нажата кнопка. –
thesayhey