epi.log epi.log - 5 days ago 4x
Python Question

Transform a base 64 encoded string into a downloadable pdf using django rest framework

I have a django/python3 application that requests the Limesurvey API and gets a base 64 encoded string as result.
I'd like to return this result as a downloadable pdf file.

Here's my current implementation that's simply display the base 64 string into a blank page...

data = limesurvey.export_responses_by_token(survey_id, token)
response = HttpResponse(data, content_type='application/pdf')
return StreamingHttpResponse(response)

Any help would be very appreciated!


Three steps:

Dump your base64 content into StringIO

import cStringIO as StringIO
buffer = StringIO.StringIO()

Send response with proper header

from django.http import HttpResponse
from wsgiref.util import FileWrapper

# generate the file
response = HttpResponse(FileWrapper(buffer.getvalue()), content_type='application/zip')
response['Content-Disposition'] = 'attachment; filename=MY_FILE_NAME.zip'
return response

Configure your server

Beyond the scope of django.

e.g. for nginx, refer to this link


After testing your content in some online converter, I'm sure that's base64 stuff.

However, the reason why it doesn't work remains unknown until further information is provided.

My mock snippet is like this.

>>> test_str = 'test'
>>> base_64 = test_str.encode('base64')
>>> base_64.decode('base64')
>>> base_64