From 2cf425d8a302f6e04c9e4549648be1def55d5ed9 Mon Sep 17 00:00:00 2001 From: Clay McClure Date: Wed, 29 Feb 2012 04:50:20 -0500 Subject: [PATCH] Wrap ContentFile in a file-like object with a filename and content_type. This extra layer of indirection allows us to tack some attributes (name and content_type) onto the underlying file, which we cannot do with a StringIO since it's a native ctype. These attributes are used by various third-party software that expects to work with django.core.files.File instances, and not directly with StringIO instances. By way of example, the django-storages mosso backend (CloudFilesStorage) looks for a content_type attribute, and the cloudfiles Object backend looks for a name attribute. --- AUTHORS | 2 ++ imagekit/generators.py | 21 ++++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/AUTHORS b/AUTHORS index 8263ccc..129596e 100644 --- a/AUTHORS +++ b/AUTHORS @@ -23,6 +23,7 @@ Contributors * `Timothée Peignier`_ * `Madis Väin`_ * `Jan Sagemüller`_ +* `Clay McClure`_ .. _Justin Driscoll: http://github.com/jdriscoll .. _HZDG: http://hzdg.com @@ -40,3 +41,4 @@ Contributors .. _Timothée Peignier: http://github.com/cyberdelia .. _Madis Väin: http://github.com/madisvain .. _Jan Sagemüller: https://github.com/version2 +.. _Clay McClure: https://github.com/claymation diff --git a/imagekit/generators.py b/imagekit/generators.py index bf012e1..a53bf09 100644 --- a/imagekit/generators.py +++ b/imagekit/generators.py @@ -1,4 +1,6 @@ +import mimetypes import os + from StringIO import StringIO from django.core.files.base import ContentFile @@ -9,6 +11,23 @@ from .utils import img_to_fobj, open_image, \ UnknownExtensionError +class SpecFile(ContentFile): + """ + Wraps a ContentFile in a file-like object with a filename + and a content_type. + """ + def __init__(self, filename, content): + self.file = ContentFile(content) + self.file.name = filename + try: + self.file.content_type = mimetypes.guess_type(filename)[0] + except IndexError: + self.file.content_type = None + + def __str__(self): + return self.file.name + + class SpecFileGenerator(object): def __init__(self, processors=None, format=None, options={}, autoconvert=True, storage=None): @@ -50,7 +69,7 @@ class SpecFileGenerator(object): options.items()) imgfile = img_to_fobj(img, format, **options) - content = ContentFile(imgfile.read()) + content = SpecFile(filename, imgfile.read()) return img, content def suggest_extension(self, name):