files.py 18 KB

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