files.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. import datetime
  2. import os
  3. import warnings
  4. from inspect import getargspec
  5. from django import forms
  6. from django.core import checks
  7. from django.core.files.base import File
  8. from django.core.files.images import ImageFile
  9. from django.core.files.storage import default_storage
  10. from django.db.models import signals
  11. from django.db.models.fields import Field
  12. from django.utils import six
  13. from django.utils.deprecation import RemovedInDjango20Warning
  14. from django.utils.encoding import force_str, force_text
  15. from django.utils.translation import ugettext_lazy as _
  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. return hash(self.name)
  33. # The standard File contains most of the necessary properties, but
  34. # FieldFiles can be instantiated without a name, so that needs to
  35. # be checked for here.
  36. def _require_file(self):
  37. if not self:
  38. raise ValueError("The '%s' attribute has no file associated with it." % self.field.name)
  39. def _get_file(self):
  40. self._require_file()
  41. if not hasattr(self, '_file') or self._file is None:
  42. self._file = self.storage.open(self.name, 'rb')
  43. return self._file
  44. def _set_file(self, file):
  45. self._file = file
  46. def _del_file(self):
  47. del self._file
  48. file = property(_get_file, _set_file, _del_file)
  49. def _get_path(self):
  50. self._require_file()
  51. return self.storage.path(self.name)
  52. path = property(_get_path)
  53. def _get_url(self):
  54. self._require_file()
  55. return self.storage.url(self.name)
  56. url = property(_get_url)
  57. def _get_size(self):
  58. self._require_file()
  59. if not self._committed:
  60. return self.file.size
  61. return self.storage.size(self.name)
  62. size = property(_get_size)
  63. def open(self, mode='rb'):
  64. self._require_file()
  65. self.file.open(mode)
  66. # open() doesn't alter the file's contents, but it does reset the pointer
  67. open.alters_data = True
  68. # In addition to the standard File API, FieldFiles have extra methods
  69. # to further manipulate the underlying file, as well as update the
  70. # associated model instance.
  71. def save(self, name, content, save=True):
  72. name = self.field.generate_filename(self.instance, name)
  73. args, varargs, varkw, defaults = getargspec(self.storage.save)
  74. if 'max_length' in args:
  75. self.name = self.storage.save(name, content, max_length=self.field.max_length)
  76. else:
  77. warnings.warn(
  78. 'Backwards compatibility for storage backends without '
  79. 'support for the `max_length` argument in '
  80. 'Storage.save() will be removed in Django 2.0.',
  81. RemovedInDjango20Warning, stacklevel=2
  82. )
  83. self.name = self.storage.save(name, content)
  84. setattr(self.instance, self.field.name, self.name)
  85. # Update the filesize cache
  86. self._size = content.size
  87. self._committed = True
  88. # Save the object because it has changed, unless save is False
  89. if save:
  90. self.instance.save()
  91. save.alters_data = True
  92. def delete(self, save=True):
  93. if not self:
  94. return
  95. # Only close the file if it's already open, which we know by the
  96. # presence of self._file
  97. if hasattr(self, '_file'):
  98. self.close()
  99. del self.file
  100. self.storage.delete(self.name)
  101. self.name = None
  102. setattr(self.instance, self.field.name, self.name)
  103. # Delete the filesize cache
  104. if hasattr(self, '_size'):
  105. del self._size
  106. self._committed = False
  107. if save:
  108. self.instance.save()
  109. delete.alters_data = True
  110. def _get_closed(self):
  111. file = getattr(self, '_file', None)
  112. return file is None or file.closed
  113. closed = property(_get_closed)
  114. def close(self):
  115. file = getattr(self, '_file', None)
  116. if file is not None:
  117. file.close()
  118. def __getstate__(self):
  119. # FieldFile needs access to its associated model field and an instance
  120. # it's attached to in order to work properly, but the only necessary
  121. # data to be pickled is the file's name itself. Everything else will
  122. # be restored later, by FileDescriptor below.
  123. return {'name': self.name, 'closed': False, '_committed': True, '_file': None}
  124. class FileDescriptor(object):
  125. """
  126. The descriptor for the file attribute on the model instance. Returns a
  127. FieldFile when accessed so you can do stuff like::
  128. >>> from myapp.models import MyModel
  129. >>> instance = MyModel.objects.get(pk=1)
  130. >>> instance.file.size
  131. Assigns a file object on assignment so you can do::
  132. >>> with open('/tmp/hello.world', 'r') as f:
  133. ... instance.file = File(f)
  134. """
  135. def __init__(self, field):
  136. self.field = field
  137. def __get__(self, instance=None, owner=None):
  138. if instance is None:
  139. raise AttributeError(
  140. "The '%s' attribute can only be accessed from %s instances."
  141. % (self.field.name, owner.__name__))
  142. # This is slightly complicated, so worth an explanation.
  143. # instance.file`needs to ultimately return some instance of `File`,
  144. # probably a subclass. Additionally, this returned object needs to have
  145. # the FieldFile API so that users can easily do things like
  146. # instance.file.path and have that delegated to the file storage engine.
  147. # Easy enough if we're strict about assignment in __set__, but if you
  148. # peek below you can see that we're not. So depending on the current
  149. # value of the field we have to dynamically construct some sort of
  150. # "thing" to return.
  151. # The instance dict contains whatever was originally assigned
  152. # in __set__.
  153. file = instance.__dict__[self.field.name]
  154. # If this value is a string (instance.file = "path/to/file") or None
  155. # then we simply wrap it with the appropriate attribute class according
  156. # to the file field. [This is FieldFile for FileFields and
  157. # ImageFieldFile for ImageFields; it's also conceivable that user
  158. # subclasses might also want to subclass the attribute class]. This
  159. # object understands how to convert a path to a file, and also how to
  160. # handle None.
  161. if isinstance(file, six.string_types) or file is None:
  162. attr = self.field.attr_class(instance, self.field, file)
  163. instance.__dict__[self.field.name] = attr
  164. # Other types of files may be assigned as well, but they need to have
  165. # the FieldFile interface added to them. Thus, we wrap any other type of
  166. # File inside a FieldFile (well, the field's attr_class, which is
  167. # usually FieldFile).
  168. elif isinstance(file, File) and not isinstance(file, FieldFile):
  169. file_copy = self.field.attr_class(instance, self.field, file.name)
  170. file_copy.file = file
  171. file_copy._committed = False
  172. instance.__dict__[self.field.name] = file_copy
  173. # Finally, because of the (some would say boneheaded) way pickle works,
  174. # the underlying FieldFile might not actually itself have an associated
  175. # file. So we need to reset the details of the FieldFile in those cases.
  176. elif isinstance(file, FieldFile) and not hasattr(file, 'field'):
  177. file.instance = instance
  178. file.field = self.field
  179. file.storage = self.field.storage
  180. # That was fun, wasn't it?
  181. return instance.__dict__[self.field.name]
  182. def __set__(self, instance, value):
  183. instance.__dict__[self.field.name] = value
  184. class FileField(Field):
  185. # The class to wrap instance attributes in. Accessing the file object off
  186. # the instance will always return an instance of attr_class.
  187. attr_class = FieldFile
  188. # The descriptor to use for accessing the attribute off of the class.
  189. descriptor_class = FileDescriptor
  190. description = _("File")
  191. def __init__(self, verbose_name=None, name=None, upload_to='', storage=None, **kwargs):
  192. self._primary_key_set_explicitly = 'primary_key' in kwargs
  193. self._unique_set_explicitly = 'unique' in kwargs
  194. self.storage = storage or default_storage
  195. self.upload_to = upload_to
  196. kwargs['max_length'] = kwargs.get('max_length', 100)
  197. super(FileField, self).__init__(verbose_name, name, **kwargs)
  198. def check(self, **kwargs):
  199. errors = super(FileField, self).check(**kwargs)
  200. errors.extend(self._check_unique())
  201. errors.extend(self._check_primary_key())
  202. return errors
  203. def _check_unique(self):
  204. if self._unique_set_explicitly:
  205. return [
  206. checks.Error(
  207. "'unique' is not a valid argument for a %s." % self.__class__.__name__,
  208. hint=None,
  209. obj=self,
  210. id='fields.E200',
  211. )
  212. ]
  213. else:
  214. return []
  215. def _check_primary_key(self):
  216. if self._primary_key_set_explicitly:
  217. return [
  218. checks.Error(
  219. "'primary_key' is not a valid argument for a %s." % self.__class__.__name__,
  220. hint=None,
  221. obj=self,
  222. id='fields.E201',
  223. )
  224. ]
  225. else:
  226. return []
  227. def deconstruct(self):
  228. name, path, args, kwargs = super(FileField, self).deconstruct()
  229. if kwargs.get("max_length", None) == 100:
  230. del kwargs["max_length"]
  231. kwargs['upload_to'] = self.upload_to
  232. if self.storage is not default_storage:
  233. kwargs['storage'] = self.storage
  234. return name, path, args, kwargs
  235. def get_internal_type(self):
  236. return "FileField"
  237. def get_prep_lookup(self, lookup_type, value):
  238. if hasattr(value, 'name'):
  239. value = value.name
  240. return super(FileField, self).get_prep_lookup(lookup_type, value)
  241. def get_prep_value(self, value):
  242. "Returns field's value prepared for saving into a database."
  243. value = super(FileField, self).get_prep_value(value)
  244. # Need to convert File objects provided via a form to unicode for database insertion
  245. if value is None:
  246. return None
  247. return six.text_type(value)
  248. def pre_save(self, model_instance, add):
  249. "Returns field's value just before saving."
  250. file = super(FileField, self).pre_save(model_instance, add)
  251. if file and not file._committed:
  252. # Commit the file to storage prior to saving the model
  253. file.save(file.name, file, save=False)
  254. return file
  255. def contribute_to_class(self, cls, name, **kwargs):
  256. super(FileField, self).contribute_to_class(cls, name, **kwargs)
  257. setattr(cls, self.name, self.descriptor_class(self))
  258. def get_directory_name(self):
  259. return os.path.normpath(force_text(datetime.datetime.now().strftime(force_str(self.upload_to))))
  260. def get_filename(self, filename):
  261. return os.path.normpath(self.storage.get_valid_name(os.path.basename(filename)))
  262. def generate_filename(self, instance, filename):
  263. # If upload_to is a callable, make sure that the path it returns is
  264. # passed through get_valid_name() of the underlying storage.
  265. if callable(self.upload_to):
  266. directory_name, filename = os.path.split(self.upload_to(instance, filename))
  267. filename = self.storage.get_valid_name(filename)
  268. return os.path.normpath(os.path.join(directory_name, filename))
  269. return os.path.join(self.get_directory_name(), self.get_filename(filename))
  270. def save_form_data(self, instance, data):
  271. # Important: None means "no change", other false value means "clear"
  272. # This subtle distinction (rather than a more explicit marker) is
  273. # needed because we need to consume values that are also sane for a
  274. # regular (non Model-) Form to find in its cleaned_data dictionary.
  275. if data is not None:
  276. # This value will be converted to unicode and stored in the
  277. # database, so leaving False as-is is not acceptable.
  278. if not data:
  279. data = ''
  280. setattr(instance, self.name, data)
  281. def formfield(self, **kwargs):
  282. defaults = {'form_class': forms.FileField, 'max_length': self.max_length}
  283. # If a file has been provided previously, then the form doesn't require
  284. # that a new file is provided this time.
  285. # The code to mark the form field as not required is used by
  286. # form_for_instance, but can probably be removed once form_for_instance
  287. # is gone. ModelForm uses a different method to check for an existing file.
  288. if 'initial' in kwargs:
  289. defaults['required'] = False
  290. defaults.update(kwargs)
  291. return super(FileField, self).formfield(**defaults)
  292. class ImageFileDescriptor(FileDescriptor):
  293. """
  294. Just like the FileDescriptor, but for ImageFields. The only difference is
  295. assigning the width/height to the width_field/height_field, if appropriate.
  296. """
  297. def __set__(self, instance, value):
  298. previous_file = instance.__dict__.get(self.field.name)
  299. super(ImageFileDescriptor, self).__set__(instance, value)
  300. # To prevent recalculating image dimensions when we are instantiating
  301. # an object from the database (bug #11084), only update dimensions if
  302. # the field had a value before this assignment. Since the default
  303. # value for FileField subclasses is an instance of field.attr_class,
  304. # previous_file will only be None when we are called from
  305. # Model.__init__(). The ImageField.update_dimension_fields method
  306. # hooked up to the post_init signal handles the Model.__init__() cases.
  307. # Assignment happening outside of Model.__init__() will trigger the
  308. # update right here.
  309. if previous_file is not None:
  310. self.field.update_dimension_fields(instance, force=True)
  311. class ImageFieldFile(ImageFile, FieldFile):
  312. def delete(self, save=True):
  313. # Clear the image dimensions cache
  314. if hasattr(self, '_dimensions_cache'):
  315. del self._dimensions_cache
  316. super(ImageFieldFile, self).delete(save)
  317. class ImageField(FileField):
  318. attr_class = ImageFieldFile
  319. descriptor_class = ImageFileDescriptor
  320. description = _("Image")
  321. def __init__(self, verbose_name=None, name=None, width_field=None,
  322. height_field=None, **kwargs):
  323. self.width_field, self.height_field = width_field, height_field
  324. super(ImageField, self).__init__(verbose_name, name, **kwargs)
  325. def check(self, **kwargs):
  326. errors = super(ImageField, self).check(**kwargs)
  327. errors.extend(self._check_image_library_installed())
  328. return errors
  329. def _check_image_library_installed(self):
  330. try:
  331. from PIL import Image # NOQA
  332. except ImportError:
  333. return [
  334. checks.Error(
  335. 'Cannot use ImageField because Pillow is not installed.',
  336. hint=('Get Pillow at https://pypi.python.org/pypi/Pillow '
  337. 'or run command "pip install Pillow".'),
  338. obj=self,
  339. id='fields.E210',
  340. )
  341. ]
  342. else:
  343. return []
  344. def deconstruct(self):
  345. name, path, args, kwargs = super(ImageField, self).deconstruct()
  346. if self.width_field:
  347. kwargs['width_field'] = self.width_field
  348. if self.height_field:
  349. kwargs['height_field'] = self.height_field
  350. return name, path, args, kwargs
  351. def contribute_to_class(self, cls, name, **kwargs):
  352. super(ImageField, self).contribute_to_class(cls, name, **kwargs)
  353. # Attach update_dimension_fields so that dimension fields declared
  354. # after their corresponding image field don't stay cleared by
  355. # Model.__init__, see bug #11196.
  356. # Only run post-initialization dimension update on non-abstract models
  357. if not cls._meta.abstract:
  358. signals.post_init.connect(self.update_dimension_fields, sender=cls)
  359. def update_dimension_fields(self, instance, force=False, *args, **kwargs):
  360. """
  361. Updates field's width and height fields, if defined.
  362. This method is hooked up to model's post_init signal to update
  363. dimensions after instantiating a model instance. However, dimensions
  364. won't be updated if the dimensions fields are already populated. This
  365. avoids unnecessary recalculation when loading an object from the
  366. database.
  367. Dimensions can be forced to update with force=True, which is how
  368. ImageFileDescriptor.__set__ calls this method.
  369. """
  370. # Nothing to update if the field doesn't have dimension fields.
  371. has_dimension_fields = self.width_field or self.height_field
  372. if not has_dimension_fields:
  373. return
  374. # getattr will call the ImageFileDescriptor's __get__ method, which
  375. # coerces the assigned value into an instance of self.attr_class
  376. # (ImageFieldFile in this case).
  377. file = getattr(instance, self.attname)
  378. # Nothing to update if we have no file and not being forced to update.
  379. if not file and not force:
  380. return
  381. dimension_fields_filled = not(
  382. (self.width_field and not getattr(instance, self.width_field))
  383. or (self.height_field and not getattr(instance, self.height_field))
  384. )
  385. # When both dimension fields have values, we are most likely loading
  386. # data from the database or updating an image field that already had
  387. # an image stored. In the first case, we don't want to update the
  388. # dimension fields because we are already getting their values from the
  389. # database. In the second case, we do want to update the dimensions
  390. # fields and will skip this return because force will be True since we
  391. # were called from ImageFileDescriptor.__set__.
  392. if dimension_fields_filled and not force:
  393. return
  394. # file should be an instance of ImageFieldFile or should be None.
  395. if file:
  396. width = file.width
  397. height = file.height
  398. else:
  399. # No file, so clear dimensions fields.
  400. width = None
  401. height = None
  402. # Update the width and height fields.
  403. if self.width_field:
  404. setattr(instance, self.width_field, width)
  405. if self.height_field:
  406. setattr(instance, self.height_field, height)
  407. def formfield(self, **kwargs):
  408. defaults = {'form_class': forms.ImageField}
  409. defaults.update(kwargs)
  410. return super(ImageField, self).formfield(**defaults)