files.py 18 KB

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