HPE_UNEXPECTED_CONTENT_LENGTH Content-Length 到 BytesIO 长度时出错

HPE_UNEXPECTED_CONTENT_LENGTH error when Content-Length to BytesIO length

我正在将 python 金字塔项目从 python 2 移动到 3。我正在使用 ReportLab 生成 PDF 文件并将其发送到前端。根据他们的示例,我需要使用 io.BytesIO(),而以前是 StringIO()

现在使用生成的文档长度在我的响应中设置 Content-Length,我收到 HPE_UNEXPECTED_CONTENT_LENGTH 错误。

pdf = io.BytesIO()
doc = SimpleDocTemplate(pdf)
doc.build(story)
pdfcontent = pdf.getvalue()
pdf.close()

response = Response(content_type='application/pdf', body=pdfcontent)
response.headers.add("Content-Length", str(len(pdfcontent)))

如果我不设置 Content-Length 属性,下载工作正常,但我不想将其留空。

我不确定你的具体例子和错误,但我很确定当你像这样提供响应 body 字节时,金字塔发送 Content-Length header.无需手动设置,它已经有了字节,因此知道它的大小。

您应该检查响应 headers(使用浏览器开发人员工具或命令行工具,如 curl 或 httpie)。