Created
September 17, 2012 20:41
-
-
Save eloyz/3739652 to your computer and use it in GitHub Desktop.
Python String to Django File Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Using Amazon S3 with filename to get data in string and convert to file object | |
then returning HTTP response from file object with mime type. | |
""" | |
import os | |
import mimetypes | |
from django.http import Http404, HttpResponse | |
from django.core.files.base import ContentFile | |
from django.core.files.storage import default_storage | |
filename = 'blah/blah/blah/photo.jpg | |
base_name = os.path.basename(filename) | |
mime_type = mimetypes.guess_type(base_name)[0] | |
if not mime_type: | |
raise Http404 | |
if not default_storage.exists(filename): | |
raise Http404 | |
data =default_storage.open(filename).read() | |
f = ContentFile(data) | |
response = HttpResponse(f.read(), mimetype=mime_type) | |
response['Content-Disposition'] = 'filename=%s' % base_name | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment