2017-05-04 274 views
0

我正在使用xlsxwriter python包將數據從PostgreSQL數據庫導出到django項目中。我已經實現了一個Django命令來做到這一點,但問題是有超過4百萬的數據記錄,寫入文件會佔用我所有的RAM,並且進程會被終止。xlsxwriter消耗太多的內存和進程被終止

登錄:

[export_user_data_to_excel]> Generating excel file with: 
    3913616 Instagram publications 
    1250156 Instagram hashtags 
    513124 Twitter publications 
    127912 Twitter hashtags 
Killed 

我已經試過了一個名爲「constant_memory」參數,但它似乎不有所作爲。下面是寫入Excel文件的方法:

def write_to_excel_perf(filename, instagram_publications, instagram_tags, twitter_publications, twitter_tags, instance): 
    """ 
    Export the current queryset to an excel file in xlsx format. 
    Optimized for low memory consumption and better performance 
    http://xlsxwriter.readthedocs.io/working_with_memory.html#memory-perf 
    """ 
    logger.info("[write_to_excel_perf]> Openning Workbook..") 
    book = xlsxwriter.Workbook(filename, {'constant_memory': True}) 
    if 'instagram' in instance: 
     logger.info("[write_to_excel_perf]> Writting Instagram publications..") 
     sheet = book.add_worksheet('Instagram Media') 
     # Adding media page 
     titles = ["Type", "City", "Date", "Instagram Id", "Instagram URL", "caption", "likes", 
        "author", "location id", "location name", "lat", "lng"] 
     i = 0 
     for title in titles: 
      sheet.write(0, i, title) 
      i += 1 
     row_index = 1 
     # We improve the performance making sure that we query by related data using select_related 
     # and prefetch_related when needed 
     instagram_publications = instagram_publications.select_related('location__spot__city', 'author', 'location') 
     for el in instagram_publications: 
      # ["Type", "Date", "Instagram Id", "Instagram URL", "caption", "likes", "author", "author_profile", 
      #  "location id", "location name", "lat", "lng"] 
      mediaType = 'Photo' if el.mediaType == '1' else 'Video' 
      city = el.location.spot.city.name if el.location is not None and el.location.spot.city is not None else "Undefined" 
      publication_date = el.publication_date.strftime("%d/%m/%Y %H:%M") 
      username = el.author.username if el.author is not None else "Undefined" 
      location_id = el.location.instagramID if el.location is not None else "Undefined" 
      location_name = el.location.name if el.location is not None else "Undefined" 
      location_lat = el.location.position.y if el.location is not None else "Undefined" 
      location_lng = el.location.position.x if el.location is not None else "Undefined" 

      row = [mediaType, city, publication_date, el.instagramID, el.instagram_url, el.caption, el.likes, 
        username, location_id, location_name, location_lat, 
        location_lng] 
      column_index = 0 
      for value in row: 
       sheet.write(row_index, column_index, value) 
       column_index += 1 
      row_index += 1 

     # Adding tag page 
     sheet = book.add_worksheet('Instagram Tags') 
     titles = ["Hashtag", "Quantity"] 
     i = 0 
     for title in titles: 
      sheet.write(0, i, title) 
      i += 1 
     row_index = 1 
     if instagram_tags is not None: 
      logger.info("[write_to_excel_perf]> Writting Instagram hashtags..") 
      for el in instagram_tags: 
       hashtag_id = el.get('hashtag__id') 
       label = Hashtag.objects.get(id=hashtag_id).label 
       sheet.write(row_index, 0, label) 
       sheet.write(row_index, 1, el.get('count')) 
       row_index += 1 
     else: 
      sheet.write(1, 0, "No hashtags in query") 

    if 'twitter' in instance: 
     # TwitterPublication 
     logger.info("[write_to_excel_perf]> Writting Twitter publications..") 
     sheet = book.add_worksheet('Twitter Media') 

     titles = ["City", "Date", "Twitter Id", "Twitter URL", "caption", "likes", 
        "author", "lat", "lng"] 
     i = 0 
     for title in titles: 
      sheet.write(0, i, title) 
      i += 1 
     row_index = 1 

     twitter_publications = twitter_publications.select_related('location__spot__city', 'author', 'location') 
     for el in twitter_publications: 
      city = el.location.spot.city.name if el.location is not None and el.location.spot.city is not None else "Undefined" 
      publication_date = el.publication_date.strftime("%d/%m/%Y %H:%M") 
      username = el.author.username if el.author is not None else "Undefined" 
      location_lat = el.location.position.y if el.location is not None else "Undefined" 
      location_lng = el.location.position.x if el.location is not None else "Undefined" 

      row = [city, publication_date, el.twitterID, el.twitter_url, el.caption, el.likes, 
        username, location_lat, location_lng] 
      column_index = 0 
      for value in row: 
       sheet.write(row_index, column_index, value) 
       column_index += 1 
      row_index += 1 

     # Adding tag page 
     sheet = book.add_worksheet('Twitter Tags') 
     titles = ["Hashtag", "Quantity"] 
     i = 0 
     for title in titles: 
      sheet.write(0, i, title) 
      i += 1 
     row_index = 1 
     if twitter_tags is not None: 
      logger.info("[write_to_excel_perf]> Writting Twitter hashtags..") 
      for el in twitter_tags: 
       hashtag_id = el.get('hashtag__id') 
       label = TwitterHashtag.objects.get(id=hashtag_id).label 
       sheet.write(row_index, 0, label) 
       sheet.write(row_index, 1, el.get('count')) 
       row_index += 1 
     else: 
      sheet.write(1, 0, "No hashtags in query") 

    book.close() 

    logger.info("[write_to_excel_perf]> Export file generated sucessfully.") 
    return book 

回答

1

我曾與一個叫constant_memory參數嘗試,但它似乎不有所作爲。

它應該這樣做。如XlsxWriter Documentation所示,constant_memory選項可保持內存使用量不變且很小。

因此,如果它不會對您的應用程序產生影響,那麼問題可能不在於XlsxWriter,而其他內容正在耗費內存。

您可以驗證通過註釋掉所有對worksheet.write()的調用並再次運行測試。

+0

謝謝!我認爲你是對的,我仍然在調試它,但是我發現主要的問題是select_related()的使用,它將相關對象的大量數據一次性存儲到內存中。 –

+0

我想知道是否有辦法強制垃圾收集後寫每一行,因爲它似乎仍然增加,記憶仍然緩慢,但仍然增加無論如何。我不知道爲什麼,但我想這可能是相關對象的數據。 –

+1

@Mariano在'constant_memory'模式下,XlsxWriter只保留內存中的一行數據,並將數據刷新到每個新行的磁盤上。你確定XlsxWriter導致內存增加嗎? – jmcnamara