2
0

storage.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. ================
  2. File storage API
  3. ================
  4. .. module:: django.core.files.storage
  5. Getting the default storage class
  6. =================================
  7. Django provides convenient ways to access the default storage class:
  8. .. data:: storages
  9. A dictionary-like object that allows retrieving a storage instance using
  10. its alias as defined by :setting:`STORAGES`.
  11. ``storages`` has an attribute ``backends``, which defaults to the raw value
  12. provided in :setting:`STORAGES`.
  13. Additionally, ``storages`` provides a ``create_storage()`` method that
  14. accepts the dictionary used in :setting:`STORAGES` for a backend, and
  15. returns a storage instance based on that backend definition. This may be
  16. useful for third-party packages needing to instantiate storages in tests:
  17. .. code-block:: pycon
  18. >>> from django.core.files.storage import storages
  19. >>> storages.backends
  20. {'default': {'BACKEND': 'django.core.files.storage.FileSystemStorage'},
  21. 'staticfiles': {'BACKEND': 'django.contrib.staticfiles.storage.StaticFilesStorage'},
  22. 'custom': {'BACKEND': 'package.storage.CustomStorage'}}
  23. >>> storage_instance = storages.create_storage({"BACKEND": "package.storage.CustomStorage"})
  24. .. class:: DefaultStorage
  25. :class:`~django.core.files.storage.DefaultStorage` provides
  26. lazy access to the default storage system as defined by ``default`` key in
  27. :setting:`STORAGES`. :class:`DefaultStorage` uses
  28. :data:`~django.core.files.storage.storages` internally.
  29. .. data:: default_storage
  30. :data:`~django.core.files.storage.default_storage` is an instance of the
  31. :class:`~django.core.files.storage.DefaultStorage`.
  32. The ``FileSystemStorage`` class
  33. ===============================
  34. .. class:: FileSystemStorage(location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None, allow_overwrite=False)
  35. The :class:`~django.core.files.storage.FileSystemStorage` class implements
  36. basic file storage on a local filesystem. It inherits from
  37. :class:`~django.core.files.storage.Storage` and provides implementations
  38. for all the public methods thereof.
  39. .. note::
  40. The ``FileSystemStorage.delete()`` method will not raise an exception
  41. if the given file name does not exist.
  42. .. attribute:: location
  43. Absolute path to the directory that will hold the files.
  44. Defaults to the value of your :setting:`MEDIA_ROOT` setting.
  45. .. attribute:: base_url
  46. URL that serves the files stored at this location.
  47. Defaults to the value of your :setting:`MEDIA_URL` setting.
  48. .. attribute:: file_permissions_mode
  49. The file system permissions that the file will receive when it is
  50. saved. Defaults to :setting:`FILE_UPLOAD_PERMISSIONS`.
  51. .. attribute:: directory_permissions_mode
  52. The file system permissions that the directory will receive when it is
  53. saved. Defaults to :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`.
  54. .. attribute:: allow_overwrite
  55. .. versionadded:: 5.1
  56. Flag to control allowing saving a new file over an existing one.
  57. Defaults to ``False``.
  58. .. method:: get_created_time(name)
  59. Returns a :class:`~datetime.datetime` of the system's ctime, i.e.
  60. :func:`os.path.getctime`. On some systems (like Unix), this is the
  61. time of the last metadata change, and on others (like Windows), it's
  62. the creation time of the file.
  63. The ``InMemoryStorage`` class
  64. =============================
  65. .. class:: InMemoryStorage(location=None, base_url=None, file_permissions_mode=None, directory_permissions_mode=None)
  66. The :class:`~django.core.files.storage.InMemoryStorage` class implements
  67. a memory-based file storage. It has no persistence, but can be useful for
  68. speeding up tests by avoiding disk access.
  69. .. attribute:: location
  70. Absolute path to the directory name assigned to files. Defaults to the
  71. value of your :setting:`MEDIA_ROOT` setting.
  72. .. attribute:: base_url
  73. URL that serves the files stored at this location.
  74. Defaults to the value of your :setting:`MEDIA_URL` setting.
  75. .. attribute:: file_permissions_mode
  76. The file system permissions assigned to files, provided for
  77. compatibility with ``FileSystemStorage``. Defaults to
  78. :setting:`FILE_UPLOAD_PERMISSIONS`.
  79. .. attribute:: directory_permissions_mode
  80. The file system permissions assigned to directories, provided for
  81. compatibility with ``FileSystemStorage``. Defaults to
  82. :setting:`FILE_UPLOAD_DIRECTORY_PERMISSIONS`.
  83. The ``Storage`` class
  84. =====================
  85. .. class:: Storage
  86. The :class:`~django.core.files.storage.Storage` class provides a
  87. standardized API for storing files, along with a set of default
  88. behaviors that all other storage systems can inherit or override
  89. as necessary.
  90. .. note::
  91. When methods return naive ``datetime`` objects, the effective timezone
  92. used will be the current value of ``os.environ['TZ']``; note that this
  93. is usually set from Django's :setting:`TIME_ZONE`.
  94. .. method:: delete(name)
  95. Deletes the file referenced by ``name``. If deletion is not supported
  96. on the target storage system this will raise ``NotImplementedError``
  97. instead.
  98. .. method:: exists(name)
  99. Returns ``True`` if a file referenced by the given name already exists
  100. in the storage system.
  101. .. method:: get_accessed_time(name)
  102. Returns a :class:`~datetime.datetime` of the last accessed time of the
  103. file. For storage systems unable to return the last accessed time this
  104. will raise :exc:`NotImplementedError`.
  105. If :setting:`USE_TZ` is ``True``, returns an aware ``datetime``,
  106. otherwise returns a naive ``datetime`` in the local timezone.
  107. .. method:: get_alternative_name(file_root, file_ext)
  108. Returns an alternative filename based on the ``file_root`` and
  109. ``file_ext`` parameters, an underscore plus a random 7 character
  110. alphanumeric string is appended to the filename before the extension.
  111. .. method:: get_available_name(name, max_length=None)
  112. Returns a filename based on the ``name`` parameter that's free and
  113. available for new content to be written to on the target storage
  114. system.
  115. The length of the filename will not exceed ``max_length``, if provided.
  116. If a free unique filename cannot be found, a
  117. :exc:`SuspiciousFileOperation
  118. <django.core.exceptions.SuspiciousOperation>` exception will be raised.
  119. If a file with ``name`` already exists, :meth:`get_alternative_name` is
  120. called to obtain an alternative name.
  121. .. method:: get_created_time(name)
  122. Returns a :class:`~datetime.datetime` of the creation time of the file.
  123. For storage systems unable to return the creation time this will raise
  124. :exc:`NotImplementedError`.
  125. If :setting:`USE_TZ` is ``True``, returns an aware ``datetime``,
  126. otherwise returns a naive ``datetime`` in the local timezone.
  127. .. method:: get_modified_time(name)
  128. Returns a :class:`~datetime.datetime` of the last modified time of the
  129. file. For storage systems unable to return the last modified time this
  130. will raise :exc:`NotImplementedError`.
  131. If :setting:`USE_TZ` is ``True``, returns an aware ``datetime``,
  132. otherwise returns a naive ``datetime`` in the local timezone.
  133. .. method:: get_valid_name(name)
  134. Returns a filename based on the ``name`` parameter that's suitable
  135. for use on the target storage system.
  136. .. method:: generate_filename(filename)
  137. Validates the ``filename`` by calling :attr:`get_valid_name()` and
  138. returns a filename to be passed to the :meth:`save` method.
  139. The ``filename`` argument may include a path as returned by
  140. :attr:`FileField.upload_to <django.db.models.FileField.upload_to>`.
  141. In that case, the path won't be passed to :attr:`get_valid_name()` but
  142. will be prepended back to the resulting name.
  143. The default implementation uses :mod:`os.path` operations. Override
  144. this method if that's not appropriate for your storage.
  145. .. method:: listdir(path)
  146. Lists the contents of the specified path, returning a 2-tuple of lists;
  147. the first item being directories, the second item being files. For
  148. storage systems that aren't able to provide such a listing, this will
  149. raise a ``NotImplementedError`` instead.
  150. .. method:: open(name, mode='rb')
  151. Opens the file given by ``name``. Note that although the returned file
  152. is guaranteed to be a ``File`` object, it might actually be some
  153. subclass. In the case of remote file storage this means that
  154. reading/writing could be quite slow, so be warned.
  155. .. method:: path(name)
  156. The local filesystem path where the file can be opened using Python's
  157. standard ``open()``. For storage systems that aren't accessible from
  158. the local filesystem, this will raise ``NotImplementedError`` instead.
  159. .. method:: save(name, content, max_length=None)
  160. Saves a new file using the storage system, preferably with the name
  161. specified. If there already exists a file with this name ``name``, the
  162. storage system may modify the filename as necessary to get a unique
  163. name. The actual name of the stored file will be returned.
  164. The ``max_length`` argument is passed along to
  165. :meth:`get_available_name`.
  166. The ``content`` argument must be an instance of
  167. :class:`django.core.files.File` or a file-like object that can be
  168. wrapped in ``File``.
  169. .. method:: size(name)
  170. Returns the total size, in bytes, of the file referenced by ``name``.
  171. For storage systems that aren't able to return the file size this will
  172. raise ``NotImplementedError`` instead.
  173. .. method:: url(name)
  174. Returns the URL where the contents of the file referenced by ``name``
  175. can be accessed. For storage systems that don't support access by URL
  176. this will raise ``NotImplementedError`` instead.