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 19 KiB

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