我有一个函数,它接受一个自定义对象列表,符合某些值,然后将它们写入CSV文件。发生了一件非常奇怪的事情,当列表中只包含一些对象时,生成的CSV文件始终为空白。当列表更长时,该功能正常工作。这个临时文件可能是某种奇怪的异常吗?
我必须指出,此函数将临时文件返回给Web服务器,允许用户下载CSV。 Web服务器功能位于主要功能之下。
def makeCSV(things):
from tempfile import NamedTemporaryFile
# make the csv headers from an object
headers = [h for h in dir(things[0]) if not h.startswith('_')]
# this just pretties up the object and returns it as a dict
def cleanVals(item):
new_item = {}
for h in headers:
try:
new_item[h] = getattr(item, h)
except:
new_item[h] = ''
if isinstance(new_item[h], list):
if new_item[h]:
new_item[h] = [z.__str__() for z in new_item[h]]
new_item[h] = ', '.join(new_item[h])
else:
new_item[h] = ''
new_item[h] = new_item[h].__str__()
return new_item
things = map(cleanVals, things)
f = NamedTemporaryFile(delete=True)
dw = csv.DictWriter(f,sorted(headers),restval='',extrasaction='ignore')
dw.writer.writerow(dw.fieldnames)
for t in things:
try:
dw.writerow(t)
# I can always see the dicts here...
print t
except Exception as e:
# and there are no exceptions
print e
return f
Web服务器功能:
f = makeCSV(search_results)
response = FileResponse(f.name)
response.headers['Content-Disposition'] = (
"attachment; filename=export_%s.csv" % collection)
return response
非常感谢任何帮助或建议!
答案 0 :(得分:1)
总结eumiro的回答:文件需要刷新。在makeCSV()的末尾调用f.flush()。