0

カスタムオブジェクトのリストを取得し、いくつかの値を適合させてから、それらを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

どんな助けやアドバイスも大歓迎です!

4

1 に答える 1

1

eumiro の回答を要約すると、ファイルをフラッシュする必要があります。makeCSV() の最後に f.flush() を呼び出します。

于 2012-11-16T13:23:50.257 に答える