Python bytearray return in HttpResponse
I have a django view that I want to return an Excel file. Code below:
def get_template(request, spec_pk):
spec = get_object_or_404(Spec, pk=spec_pk)
response = HttpResponse(spec.get_template(), mimetype='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s_template.xls' % spec.name
return response
In this example, the type spec.get_template()
is - <type 'bytearray'>
, which contains the binary data of an Excel spreadsheet.
The problem is, when I try to load this view and open it with Excel, it comes in as garbled binary data. I know I am bytearray
correct because if I do the following:
f = open('temp.xls', 'wb')
f.write(spec.get_template())
I can open temp.xls
in Excel fine.
I even got to the point where I changed my view to:
def get_template(request, spec_pk):
spec = get_object_or_404(Spec, pk=spec_pk)
f = open('/home/user/temp.xls', 'wb')
f.write(spec.get_template())
f.close()
f = open('/home/user/temp.xls', 'rb')
response = HttpResponse(f.read(), mimetype='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename=%s_template.xls' % spec.name
return response
And it works great - I can open the xls file from the browser in Excel and everything is fine.
So my question is, what do I need to do so bytearray
that before I transfer it to HttpResponse
. Why does storing it as binary and then reopening it work fine, but transferring it itself bytearray
results in garbled data?
source to share
Ok, through completely random (and very persistent) trial and error, I found a solution using the python module binascii
.
It works:
response = HttpResponse(binascii.a2b_qp(spec.get_template()), mimetype='application/ms-excel')
According to the python docs for binascii.a2b_qp
:
Convert the quoted data block to binary and return binary data. Several lines can be transferred at a time. If the optional argument header is present and true, underscores will be decoded as spaces.
I wish someone could tell me why it saved it as binary and then resumed it working.
source to share