1

该片段将所有文档从我的数据库中提取出来,并将它们转储到 gzip 压缩文件中。docs_to_dump 是一个 django 对象,包含所有要转储的文本文档。

os.chdir(dump_dir)
filename = 'latest-' + court_id + '.xml.gz.part'
with myGzipFile(filename, mode='wb') as z_file:
    z_file.write('<?xml version="1.0" encoding="utf-8"?>\n<opinions dumpdate="' + str(date.today()) + '">\n')

    for doc in docs_to_dump:
        row = etree.Element("opinion",
            dateFiled           = str(doc.dateFiled),
            precedentialStatus  = doc.documentType,
            local_path          = str(doc.local_path),
            time_retrieved      = str(doc.time_retrieved),
            download_URL        = doc.download_URL,
            caseNumber          = doc.citation.caseNumber,
            caseNameShort       = doc.citation.caseNameShort,
            court               = doc.court.get_courtUUID_display(),
            sha1                = doc.documentSHA1,
            source              = doc.get_source_display(),
            id                  = str(doc.documentUUID),
        )
        if doc.documentHTML != '':
            row.text = doc.documentHTML
        else:
            row.text = doc.documentPlainText.translate(null_map)
        z_file.write('  ' + etree.tostring(row).encode('utf-8') + '\n')

    # Close things off
    z_file.write('</opinions>')

不幸的是,它也消耗了太多的内存,以至于操作系统对其进行了核对。我认为通过写入“类文件对象”,压缩文件将即时生成,并且内存将保持相对较低。相反,它占用了数百 MB,然后崩溃。

我不是压缩专家,但我的印象是整个压缩文件都存储在内存中。

我应该这样做有更好的方法吗?

编辑——整个文件在这里:https ://bitbucket.org/mlissner/search-and-awareness-platform-courtlistener/src/2ca68efd8017/data-dumps/data-dumper.py

4

1 回答 1

2

我认为安德鲁斯基可能是对的。如果您崩溃了,请尝试调整您的查询以使用迭代器方法

就像是。

docs_to_dump = Document.objects.all().order_by('court').iterator()

应该避免将整个查询集加载到内存中。

于 2011-05-23T04:11:32.563 回答