Skip to content

Instantly share code, notes, and snippets.

@eloyz
Created September 17, 2012 20:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eloyz/3739652 to your computer and use it in GitHub Desktop.
Save eloyz/3739652 to your computer and use it in GitHub Desktop.
Python String to Django File Object
"""
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