Search code examples
pythonpyramidreportlab

HPE_UNEXPECTED_CONTENT_LENGTH error when Content-Length to BytesIO length


I'm moving a python pyramid project from python 2 to 3. I was using ReportLab to generate PDF files and send it to the front end. According to their examples I need to use io.BytesIO(), when previously it was StringIO().

Now using the generated document length to set the Content-Length in my response, I get an HPE_UNEXPECTED_CONTENT_LENGTH error.

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)))

If I don't set the Content-Length attribute the download works fine, but I would rather not leave it blank.


Solution

  • I'm not sure about you particular example and error, but I'm pretty sure that when you provide the response body bytes like this, Pyramid sends the Content-Length header. No need to set it manually, it already has the bytes and therefore knows its size.

    You should check the response headers (using your browser developer tools or a command line tools like curl or httpie).