1

I am in the middle of a reporting function which will break up reports into different workbooks then zip the files and send them out to users.

At this time, I get a successful book for the second iteration, but the first iteration seems to be overridden/lost when the bytesIO object reinitializes on subsequent iterations.

    def runPullReports():
    sharedOrderFxs.sendEmail([], 'Starting..', "Running")
    
    start = datetime.date(2022, 7, 7) #now
    start += datetime.timedelta(2)#running sunday means we've already run tuesday labels


    dateList = [start + datetime.timedelta(days=x) for x in range(4)]
    food_programs = list(refModels.FoodProgram.objects.all().values_list('id', flat=True))
    pack_list = ['HOT PACK', 'COLD PACK']
    workBookList = []
    SA = refModels.ServiceArea.objects.all()
    for service_area in SA:
        fileName = str(service_area.name) + '.xlsx'
        output = BytesIO()
        book = Workbook(output, {'in_memory': True})
       ## Other Processing here irrelevant to the question

        book.close()
        output.seek(0)  
        # resetting BytesIO() buffer before we add workbooks to the list, since we're using BytesIO again in the generate_zip function
        workBookList.append((fileName, output))

    archive = generate_zip(workBookList)
    dateRange = f'{dateList[0].month}-{dateList[0].day}_{dateList[-1]}'
    #email send fnx sending archive.

The Zip/Email function:

def generate_zip(files):
zip_buffer = BytesIO()

with zipfile.ZipFile(zip_buffer, "a", zipfile.ZIP_DEFLATED, False) as zip_file:
    for fName, file in files:
        zip_file.writestr(fName, file.read())
    zip_file.close()
zip_buffer.seek(0)
return zip_buffer.getvalue()
jjulian91
  • 41
  • 3

1 Answers1

0

It might be enough to remove the output.seek(0) from your while-loop. There is no reason to reset the created BytesIO object, as you are using a independent new on in your generate_zip().

    for service_area in SA:
        fileName = str(service_area.name) + '.xlsx'
        output = BytesIO()
        
        ## Other Processing here irrelevant to the question

        book.close()
        workBookList.append((fileName, output))
JanMalte
  • 934
  • 6
  • 17
  • I will give that a go once I get this next test going -- Attempting to run `output.getvalue()` when appending it to a list so that that actual byte information is being dumped to the list not just the instance of bytesIO. – jjulian91 Jul 05 '22 at 20:56
  • `getvalue()` gave issues which will have me alter the zip function -- attempting @JanMalte 's solution. – jjulian91 Jul 05 '22 at 21:39
  • Didn't work, actually caused more issues where both books became corrupt. – jjulian91 Jul 05 '22 at 22:27