Code

Ticket #8204: filestorage.2.diff

File filestorage.2.diff, 1.5 KB (added by flosch, 6 years ago)

I extended ContentFile for usage with PIL or others .. example follows, works for me (dunno whether ContentFile is the right place for that?)

Line 
1Index: django/core/files/base.py
2===================================================================
3--- django/core/files/base.py   (revision 8291)
4+++ django/core/files/base.py   (working copy)
5@@ -4,8 +4,10 @@
6 
7 try:
8     from cStringIO import StringIO
9+    c_string_io = True
10 except ImportError:
11     from StringIO import StringIO
12+    c_string_io = False
13 
14 class File(object):
15     DEFAULT_CHUNK_SIZE = 64 * 2**10
16@@ -151,10 +153,20 @@
17     """
18     A File-like object that takes just raw content, rather than an actual file.
19     """
20-    def __init__(self, content):
21-        self.file = StringIO(content or '')
22+    def __init__(self, content = None):
23+        if c_string_io:
24+            if content:
25+                self.file = StringIO(content)
26+                self._mode = "r"
27+            else:
28+                self.file = StringIO()
29+                self._mode = "w"
30+        else:
31+            self.file = StringIO(content or '')
32+            self._mode = "w"
33         self.size = len(content or '')
34         self.file.seek(0)
35+        self._name = "contentfile"
36         self._closed = False
37 
38     def __str__(self):
39@@ -163,6 +175,17 @@
40     def __nonzero__(self):
41         return True
42 
43+    def _get_size(self):
44+        old_position = self.file.tell()
45+        self.file.seek(0, 2)
46+        size = self.file.tell()
47+        self.file.seek(old_position)
48+        return size
49+
50+    def _set_size(self, value): pass
51+
52+    size = property(_get_size, _set_size)
53+
54     def open(self, mode=None):
55         if self._closed:
56             self._closed = False