我创建了一个函数,用于使用Weasyprint创建多个PDF,将它们压缩在一起并下载zip文件。当尝试使用内部zip程序在Windows 10上提取文件夹时,出现此错误:
“意外错误使您无法复制文件。[...]错误0x80070057” << / p>
我可以跳过该错误,并提取文件。但是,在最佳情况下,我想防止出现此错误。
def get_all_shareholder_reports(request):
current_shareholders = list(models.objects.all())
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "a") as zip_file:
for shareholder in current_shareholders:
pdf_file_handle = io.BytesIO()
context_dict = get_report_details(pk=shareholder.shareholder_id)
html_string = render_to_string('template.html',
context_dict)
html_handler = HTML(string=html_string, base_url=request.build_absolute_uri())
html_handler.write_pdf(target=pdf_file_handle)
pdf_file_handle.seek(0)
pdf_string = pdf_file_handle.getvalue()
pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
context_dict['shareholder'].surname,
datetime.datetime.now().strftime(
"%d_%m_%Y_%H:%M:%S"))
zip_file.writestr(zinfo_or_arcname=pdf_file_name, data=pdf_string)
zip_buffer.seek(0)
response = HttpResponse(zip_buffer.getvalue(), content_type="application/x-zip-compressed")
response['Content-Disposition'] = 'attachment; filename=%s' % 'myzip.zip'
return response
答案 0 :(得分:1)
您基本上需要清除Windows中所有保留字符的文件名:https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions
因此,以下应"filename".replaceAll("[<>:\"/\\\\|?*]", "")
答案 1 :(得分:0)
我发现:zip文件不喜欢文件名中的“:”。删除它们可以解决问题。
pdf_file_name ='Shareholder_Report_{}_{}_{}.pdf'.format(context_dict['shareholder'].forename,
context_dict['shareholder'].surname,
datetime.datetime.now().strftime(
"%d_%m_%Y_%H_%M_%S"))