You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

files.py 17KB

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