2011-05-23 28 views
1

這段代碼將所有文檔從我的數據庫中提取出來,並將它們轉儲到gzip壓縮文件中。 docs_to_dump是一個包含所有要轉儲的文本文檔的django對象。如何使這個Python腳本內存有效

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

+0

什麼是myGzipFile? – 2011-05-23 03:06:00

+0

你如何檢索'docs_to_dump'?它是通過'.objects.all()'進行數據庫查詢嗎? – 2011-05-23 03:10:56

+0

真的沒什麼。通過給它一個__exit__函數來支持with語句。 – mlissner 2011-05-23 03:11:22

回答

2

我想andrewski可能是正確的。如果您正在崩潰,請嘗試調整您的查詢以使用方法iterator方法

類似。

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

應該避免將整個Queryset加載到內存中。

+0

+1我懷疑是相同的,這就是爲什麼我早些時候問過「如果你寫入一個未壓縮的文件,它會消耗更少的內存嗎?」在看到迭代器方法的文檔後,我認爲這是最可能的罪魁禍首。 – 2011-05-23 04:19:36

+0

試過了。沒有什麼區別,所以我輸入了一些打印語句並做了一些分析。錯誤發生在壓縮之前,所以我在這裏使用了迭代器代碼,它的工作原理是:http://djangosnippets.org/snippets/1949/。感謝您讓我走向正確的方向。 – mlissner 2011-05-23 06:53:14