Debian Codegraph @

docs/ref/files/storage.txt

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