0

我有一个函数,它需要一个自定义对象列表,符合一些值,然后将它们写入 CSV 文件。发生了一些非常奇怪的事情,当列表仅包含几个对象时,生成的 CSV 文件始终为空白。当列表较长时,该功能可以正常工作。临时文件可能是某种奇怪的异常吗?

我必须指出,此函数将临时文件返回到允许用户下载 CSV 的 Web 服务器。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

网络服务器功能:

    f = makeCSV(search_results)
    response = FileResponse(f.name)
    response.headers['Content-Disposition'] = (
            "attachment; filename=export_%s.csv" % collection)
    return response

非常感谢任何帮助或建议!

4

1 回答 1

1

总结eumiro的回答:文件需要刷新。在 makeCSV() 结束时调用 f.flush()。

于 2012-11-16T13:23:50.257 回答