files.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import datetime
  2. import os
  3. import django.utils.copycompat as copy
  4. from django.conf import settings
  5. from django.db.models.fields import Field
  6. from django.core.files.base import File, ContentFile
  7. from django.core.files.storage import default_storage
  8. from django.core.files.images import ImageFile, get_image_dimensions
  9. from django.core.files.uploadedfile import UploadedFile
  10. from django.utils.functional import curry
  11. from django.db.models import signals
  12. from django.utils.encoding import force_unicode, smart_str
  13. from django.utils.translation import ugettext_lazy, ugettext as _
  14. from django import forms
  15. from django.db.models.loading import cache
  16. class FieldFile(File):
  17. def __init__(self, instance, field, name):
  18. super(FieldFile, self).__init__(None, name)
  19. self.instance = instance
  20. self.field = field
  21. self.storage = field.storage
  22. self._committed = True
  23. def __eq__(self, other):
  24. # Older code may be expecting FileField values to be simple strings.
  25. # By overriding the == operator, it can remain backwards compatibility.
  26. if hasattr(other, 'name'):
  27. return self.name == other.name
  28. return self.name == other
  29. def __ne__(self, other):
  30. return not self.__eq__(other)
  31. def __hash__(self):
  32. # Required because we defined a custom __eq__.
  33. return hash(self.name)
  34. # The standard File contains most of the necessary properties, but
  35. # FieldFiles can be instantiated without a name, so that needs to
  36. # be checked for here.
  37. def _require_file(self):
  38. if not self:
  39. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
  40. def _get_file(self):
  41. self._require_file()
  42. if not hasattr(self, '_file') or self._file is None:
  43. self._file = self.storage.open(self.name, 'rb')
  44. return self._file
  45. def _set_file(self, file):
  46. self._file = file
  47. def _del_file(self):
  48. del self._file
  49. file = property(_get_file, _set_file, _del_file)
  50. def _get_path(self):
  51. self._require_file()
  52. return self.storage.path(self.name)
  53. path = property(_get_path)
  54. def _get_url(self):
  55. self._require_file()
  56. return self.storage.url(self.name)
  57. url = property(_get_url)
  58. def _get_size(self):
  59. self._require_file()
  60. if not self._committed:
  61. return self.file.size
  62. return self.storage.size(self.name)
  63. size = property(_get_size)
  64. def open(self, mode='rb'):
  65. self._require_file()
  66. self.file.open(mode)
  67. # open() doesn't alter the file's contents, but it does reset the pointer
  68. open.alters_data = True
  69. # In addition to the standard File API, FieldFiles have extra methods
  70. # to further manipulate the underlying file, as well as update the
  71. # associated model instance.
  72. def save(self, name, content, save=True):
  73. name = self.field.generate_filename(self.instance, name)
  74. self.name = self.storage.save(name, content)
  75. setattr(self.instance, self.field.name, self.name)
  76. # Update the filesize cache
  77. self._size = content.size
  78. self._committed = True
  79. # Save the object because it has changed, unless save is False
  80. if save:
  81. self.instance.save()
  82. save.alters_data = True
  83. def delete(self, save=True):
  84. # Only close the file if it's already open, which we know by the
  85. # presence of self._file
  86. if hasattr(self, '_file'):
  87. self.close()
  88. del self.file
  89. self.storage.delete(self.name)
  90. self.name = None
  91. setattr(self.instance, self.field.name, self.name)
  92. # Delete the filesize cache
  93. if hasattr(self, '_size'):
  94. del self._size
  95. self._committed = False
  96. if save:
  97. self.instance.save()
  98. delete.alters_data = True
  99. def _get_closed(self):
  100. file = getattr(self, '_file', None)
  101. return file is None or file.closed
  102. closed = property(_get_closed)
  103. def close(self):
  104. file = getattr(self, '_file', None)
  105. if file is not None:
  106. file.close()
  107. def __getstate__(self):
  108. # FieldFile needs access to its associated model field and an instance
  109. # it's attached to in order to work properly, but the only necessary
  110. # data to be pickled is the file's name itself. Everything else will
  111. # be restored later, by FileDescriptor below.
  112. return {'name': self.name, 'closed': False, '_committed': True, '_file': None}
  113. class FileDescriptor(object):
  114. """
  115. The descriptor for the file attribute on the model instance. Returns a
  116. FieldFile when accessed so you can do stuff like::
  117. >>> instance.file.size
  118. Assigns a file object on assignment so you can do::
  119. >>> instance.file = File(...)
  120. """
  121. def __init__(self, field):
  122. self.field = field
  123. def __get__(self, instance=None, owner=None):
  124. if instance is None:
  125. raise AttributeError(
  126. "The '%s' attribute can only be accessed from %s instances."
  127. % (self.field.name, owner.__name__))
  128. # This is slightly complicated, so worth an explanation.
  129. # instance.file`needs to ultimately return some instance of `File`,
  130. # probably a subclass. Additionally, this returned object needs to have
  131. # the FieldFile API so that users can easily do things like
  132. # instance.file.path and have that delegated to the file storage engine.
  133. # Easy enough if we're strict about assignment in __set__, but if you
  134. # peek below you can see that we're not. So depending on the current
  135. # value of the field we have to dynamically construct some sort of
  136. # "thing" to return.
  137. # The instance dict contains whatever was originally assigned
  138. # in __set__.
  139. file = instance.__dict__[self.field.name]
  140. # If this value is a string (instance.file = "path/to/file") or None
  141. # then we simply wrap it with the appropriate attribute class according
  142. # to the file field. [This is FieldFile for FileFields and
  143. # ImageFieldFile for ImageFields; it's also conceivable that user
  144. # subclasses might also want to subclass the attribute class]. This
  145. # object understands how to convert a path to a file, and also how to
  146. # handle None.
  147. if isinstance(file, basestring) or file is None:
  148. attr = self.field.attr_class(instance, self.field, file)
  149. instance.__dict__[self.field.name] = attr
  150. # Other types of files may be assigned as well, but they need to have
  151. # the FieldFile interface added to the. Thus, we wrap any other type of
  152. # File inside a FieldFile (well, the field's attr_class, which is
  153. # usually FieldFile).
  154. elif isinstance(file, File) and not isinstance(file, FieldFile):
  155. file_copy = self.field.attr_class(instance, self.field, file.name)
  156. file_copy.file = file
  157. file_copy._committed = False
  158. instance.__dict__[self.field.name] = file_copy
  159. # Finally, because of the (some would say boneheaded) way pickle works,
  160. # the underlying FieldFile might not actually itself have an associated
  161. # file. So we need to reset the details of the FieldFile in those cases.
  162. elif isinstance(file, FieldFile) and not hasattr(file, 'field'):
  163. file.instance = instance
  164. file.field = self.field
  165. file.storage = self.field.storage
  166. # That was fun, wasn't it?
  167. return instance.__dict__[self.field.name]
  168. def __set__(self, instance, value):
  169. instance.__dict__[self.field.name] = value
  170. class FileField(Field):
  171. # The class to wrap instance attributes in. Accessing the file object off
  172. # the instance will always return an instance of attr_class.
  173. attr_class = FieldFile
  174. # The descriptor to use for accessing the attribute off of the class.
  175. descriptor_class = FileDescriptor
  176. description = ugettext_lazy("File path")
  177. def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
  178. for arg in ('primary_key', 'unique'):
  179. if arg in kwargs:
  180. raise TypeError("'%s' is not a valid argument for %s." % (arg, self.__class__))
  181. self.storage = storage or default_storage
  182. self.upload_to = upload_to
  183. if callable(upload_to):
  184. self.generate_filename = upload_to
  185. kwargs['max_length'] = kwargs.get('max_length', 100)
  186. super(FileField, self).__init__(verbose_name, name, **kwargs)
  187. def get_internal_type(self):
  188. return "FileField"
  189. def get_prep_lookup(self, lookup_type, value):
  190. if hasattr(value, 'name'):
  191. value = value.name
  192. return super(FileField, self).get_prep_lookup(lookup_type, value)
  193. def get_prep_value(self, value):
  194. "Returns field's value prepared for saving into a database."
  195. # Need to convert File objects provided via a form to unicode for database insertion
  196. if value is None:
  197. return None
  198. return unicode(value)
  199. def pre_save(self, model_instance, add):
  200. "Returns field's value just before saving."
  201. file = super(FileField, self).pre_save(model_instance, add)
  202. if file and not file._committed:
  203. # Commit the file to storage prior to saving the model
  204. file.save(file.name, file, save=False)
  205. return file
  206. def contribute_to_class(self, cls, name):
  207. super(FileField, self).contribute_to_class(cls, name)
  208. setattr(cls, self.name, self.descriptor_class(self))
  209. def get_directory_name(self):
  210. return os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart_str(self.upload_to))))
  211. def get_filename(self, filename):
  212. return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
  213. def generate_filename(self, instance, filename):
  214. return os.path.join(self.get_directory_name(), self.get_filename(filename))
  215. def save_form_data(self, instance, data):
  216. # Important: None means "no change", other false value means "clear"
  217. # This subtle distinction (rather than a more explicit marker) is
  218. # needed because we need to consume values that are also sane for a
  219. # regular (non Model-) Form to find in its cleaned_data dictionary.
  220. if data is not None:
  221. # This value will be converted to unicode and stored in the
  222. # database, so leaving False as-is is not acceptable.
  223. if not data:
  224. data = ''
  225. setattr(instance, self.name, data)
  226. def formfield(self, **kwargs):
  227. defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
  228. # If a file has been provided previously, then the form doesn't require
  229. # that a new file is provided this time.
  230. # The code to mark the form field as not required is used by
  231. # form_for_instance, but can probably be removed once form_for_instance
  232. # is gone. ModelForm uses a different method to check for an existing file.
  233. if 'initial' in kwargs:
  234. defaults['required'] = False
  235. defaults.update(kwargs)
  236. return super(FileField, self).formfield(**defaults)
  237. class ImageFileDescriptor(FileDescriptor):
  238. """
  239. Just like the FileDescriptor, but for ImageFields. The only difference is
  240. assigning the width/height to the width_field/height_field, if appropriate.
  241. """
  242. def __set__(self, instance, value):
  243. previous_file = instance.__dict__.get(self.field.name)
  244. super(ImageFileDescriptor, self).__set__(instance, value)
  245. # To prevent recalculating image dimensions when we are instantiating
  246. # an object from the database (bug #11084), only update dimensions if
  247. # the field had a value before this assignment. Since the default
  248. # value for FileField subclasses is an instance of field.attr_class,
  249. # previous_file will only be None when we are called from
  250. # Model.__init__(). The ImageField.update_dimension_fields method
  251. # hooked up to the post_init signal handles the Model.__init__() cases.
  252. # Assignment happening outside of Model.__init__() will trigger the
  253. # update right here.
  254. if previous_file is not None:
  255. self.field.update_dimension_fields(instance, force=True)
  256. class ImageFieldFile(ImageFile, FieldFile):
  257. def delete(self, save=True):
  258. # Clear the image dimensions cache
  259. if hasattr(self, '_dimensions_cache'):
  260. del self._dimensions_cache
  261. super(ImageFieldFile, self).delete(save)
  262. class ImageField(FileField):
  263. attr_class = ImageFieldFile
  264. descriptor_class = ImageFileDescriptor
  265. description = ugettext_lazy("File path")
  266. def __init__(self, verbose_name=None, name=None, width_field=None, height_field=None, **kwargs):
  267. self.width_field, self.height_field = width_field, height_field
  268. FileField.__init__(self, verbose_name, name, **kwargs)
  269. def contribute_to_class(self, cls, name):
  270. super(ImageField, self).contribute_to_class(cls, name)
  271. # Attach update_dimension_fields so that dimension fields declared
  272. # after their corresponding image field don't stay cleared by
  273. # Model.__init__, see bug #11196.
  274. signals.post_init.connect(self.update_dimension_fields, sender=cls)
  275. def update_dimension_fields(self, instance, force=False, *args, **kwargs):
  276. """
  277. Updates field's width and height fields, if defined.
  278. This method is hooked up to model's post_init signal to update
  279. dimensions after instantiating a model instance. However, dimensions
  280. won't be updated if the dimensions fields are already populated. This
  281. avoids unnecessary recalculation when loading an object from the
  282. database.
  283. Dimensions can be forced to update with force=True, which is how
  284. ImageFileDescriptor.__set__ calls this method.
  285. """
  286. # Nothing to update if the field doesn't have have dimension fields.
  287. has_dimension_fields = self.width_field or self.height_field
  288. if not has_dimension_fields:
  289. return
  290. # getattr will call the ImageFileDescriptor's __get__ method, which
  291. # coerces the assigned value into an instance of self.attr_class
  292. # (ImageFieldFile in this case).
  293. file = getattr(instance, self.attname)
  294. # Nothing to update if we have no file and not being forced to update.
  295. if not file and not force:
  296. return
  297. dimension_fields_filled = not(
  298. (self.width_field and not getattr(instance, self.width_field))
  299. or (self.height_field and not getattr(instance, self.height_field))
  300. )
  301. # When both dimension fields have values, we are most likely loading
  302. # data from the database or updating an image field that already had
  303. # an image stored. In the first case, we don't want to update the
  304. # dimension fields because we are already getting their values from the
  305. # database. In the second case, we do want to update the dimensions
  306. # fields and will skip this return because force will be True since we
  307. # were called from ImageFileDescriptor.__set__.
  308. if dimension_fields_filled and not force:
  309. return
  310. # file should be an instance of ImageFieldFile or should be None.
  311. if file:
  312. width = file.width
  313. height = file.height
  314. else:
  315. # No file, so clear dimensions fields.
  316. width = None
  317. height = None
  318. # Update the width and height fields.
  319. if self.width_field:
  320. setattr(instance, self.width_field, width)
  321. if self.height_field:
  322. setattr(instance, self.height_field, height)
  323. def formfield(self, **kwargs):
  324. defaults = {'form_class': forms.ImageField}
  325. defaults.update(kwargs)
  326. return super(ImageField, self).formfield(**defaults)