files.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. ==============
  2. Managing files
  3. ==============
  4. **New in Django development version**
  5. This document describes Django's file access APIs.
  6. By default, Django stores files locally, using the ``MEDIA_ROOT`` and
  7. ``MEDIA_URL`` settings_. The examples below assume that you're using
  8. these defaults.
  9. However, Django provides ways to write custom `file storage systems`_ that
  10. allow you to completely customize where and how Django stores files. The
  11. second half of this document describes how these storage systems work.
  12. .. _file storage systems: `File storage`_
  13. .. _settings: ../settings/
  14. Using files in models
  15. =====================
  16. When you use a `FileField`_ or `ImageField`_, Django provides a set of APIs you can use to deal with that file.
  17. .. _filefield: ../model-api/#filefield
  18. .. _imagefield: ../model-api/#imagefield
  19. Consider the following model, using a ``FileField`` to store a photo::
  20. class Car(models.Model):
  21. name = models.CharField(max_length=255)
  22. price = models.DecimalField(max_digits=5, decimal_places=2)
  23. photo = models.ImageField(upload_to='cars')
  24. Any ``Car`` instance will have a ``photo`` attribute that you can use to get at
  25. the details of the attached photo::
  26. >>> car = Car.object.get(name="57 Chevy")
  27. >>> car.photo
  28. <ImageFieldFile: chevy.jpg>
  29. >>> car.photo.name
  30. u'chevy.jpg'
  31. >>> car.photo.path
  32. u'/media/cars/chevy.jpg'
  33. >>> car.photo.url
  34. u'http://media.example.com/cars/chevy.jpg'
  35. This object -- ``car.photo`` in the example -- is a ``File`` object, which means
  36. it has all the methods and attributes described below.
  37. The ``File`` object
  38. ===================
  39. Internally, Django uses a ``django.core.files.File`` any time it needs to
  40. represent a file. This object is a thin wrapper around Python's `built-in file
  41. object`_ with some Django-specific additions.
  42. .. _built-in file object: http://docs.python.org/lib/bltin-file-objects.html
  43. Creating ``File`` instances
  44. ---------------------------
  45. Most of the time you'll simply use a ``File`` that Django's given you (i.e. a
  46. file attached to a model as above, or perhaps an `uploaded file`_).
  47. .. _uploaded file: ../upload_handling/
  48. If you need to construct a ``File`` yourself, the easiest way is to create one
  49. using a Python built-in ``file`` object::
  50. >>> from django.core.files import File
  51. # Create a Python file object using open()
  52. >>> f = open('/tmp/hello.world', 'w')
  53. >>> myfile = File(f)
  54. Now you can use any of the ``File`` attributes and methods defined below.
  55. ``File`` attributes and methods
  56. -------------------------------
  57. Django's ``File`` has the following attributes and methods:
  58. ``File.path``
  59. ~~~~~~~~~~~~~
  60. The absolute path to the file's location on a local filesystem.
  61. Custom `file storage systems`_ may not store files locally; files stored on
  62. these systems will have a ``path`` of ``None``.
  63. ``File.url``
  64. ~~~~~~~~~~~~
  65. The URL where the file can be retrieved. This is often useful in templates_; for
  66. example, a bit of a template for displaying a ``Car`` (see above) might look
  67. like::
  68. <img src='{{ car.photo.url }}' alt='{{ car.name }}' />
  69. .. _templates: ../templates/
  70. ``File.size``
  71. ~~~~~~~~~~~~~
  72. The size of the file in bytes.
  73. ``File.open(mode=None)``
  74. ~~~~~~~~~~~~~~~~~~~~~~~~
  75. Open or reopen the file (which by definition also does ``File.seek(0)``). The
  76. ``mode`` argument allows the same values as Python's standard ``open()``.
  77. When reopening a file, ``mode`` will override whatever mode the file was
  78. originally opened with; ``None`` means to reopen with the original mode.
  79. ``File.read(num_bytes=None)``
  80. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  81. Read content from the file. The optional ``size`` is the number of bytes to
  82. read; if not specified, the file will be read to the end.
  83. ``File.__iter__()``
  84. ~~~~~~~~~~~~~~~~~~~
  85. Iterate over the file yielding one line at a time.
  86. ``File.chunks(chunk_size=None)``
  87. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  88. Iterate over the file yielding "chunks" of a given size. ``chunk_size`` defaults
  89. to 64 KB.
  90. This is especially useful with very large files since it allows them to be
  91. streamed off disk and avoids storing the whole file in memory.
  92. ``File.multiple_chunks(chunk_size=None)``
  93. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  94. Returns ``True`` if the file is large enough to require multiple chunks to
  95. access all of its content give some ``chunk_size``.
  96. ``File.write(content)``
  97. ~~~~~~~~~~~~~~~~~~~~~~~
  98. Writes the specified content string to the file. Depending on the storage system
  99. behind the scenes, this content might not be fully committed until ``close()``
  100. is called on the file.
  101. ``File.close()``
  102. ~~~~~~~~~~~~~~~~
  103. Close the file.
  104. .. TODO: document the rest of the File methods.
  105. Additional ``ImageField`` attributes
  106. ------------------------------------
  107. ``File.width`` and ``File.height``
  108. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  109. These attributes provide the dimensions of the image.
  110. Additional methods on files attached to objects
  111. -----------------------------------------------
  112. Any ``File`` that's associated with an object (as with ``Car.photo``, above)
  113. will also have a couple of extra methods:
  114. ``File.save(name, content, save=True)``
  115. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  116. Saves a new file with the file name and contents provided. This will not replace
  117. the existing file, but will create a new file and update the object to point to
  118. it. If ``save`` is ``True``, the model's ``save()`` method will be called once
  119. the file is saved. That is, these two lines::
  120. >>> car.photo.save('myphoto.jpg', contents, save=False)
  121. >>> car.save()
  122. are the same as this one line::
  123. >>> car.photo.save('myphoto.jpg', contents, save=True)
  124. ``File.delete(save=True)``
  125. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  126. Remove the file from the model instance and delete the underlying file. The
  127. ``save`` argument works as above.
  128. File storage
  129. ============
  130. Behind the scenes, Django delegates decisions about how and where to store files
  131. to a file storage system. This is the object that actually understands things
  132. like file systems, opening and reading files, etc.
  133. Django's default file storage is given by the `DEFAULT_FILE_STORAGE setting`_;
  134. if you don't explicitly provide a storage system, this is the one that will be
  135. used.
  136. .. _default_file_storage setting: ../settings/#default-file-storage
  137. The built-in filesystem storage class
  138. -------------------------------------
  139. Django ships with a built-in ``FileSystemStorage`` class (defined in
  140. ``django.core.files.storage``) which implements basic local filesystem file
  141. storage. Its initializer takes two arguments:
  142. ====================== ===================================================
  143. Argument Description
  144. ====================== ===================================================
  145. ``location`` Optional. Absolute path to the directory that will
  146. hold the files. If omitted, it will be set to the
  147. value of your ``MEDIA_ROOT`` setting.
  148. ``base_url`` Optional. URL that serves the files stored at this
  149. location. If omitted, it will default to the value
  150. of your ``MEDIA_URL`` setting.
  151. ====================== ===================================================
  152. For example, the following code will store uploaded files under
  153. ``/media/photos`` regardless of what your ``MEDIA_ROOT`` setting is::
  154. from django.db import models
  155. from django.core.files.storage import FileSystemStorage
  156. fs = FileSystemStorage(location='/media/photos')
  157. class Car(models.Model):
  158. ...
  159. photo = models.ImageField(storage=fs)
  160. `Custom storage systems`_ work the same way: you can pass them in as the
  161. ``storage`` argument to a ``FileField``.
  162. .. _custom storage systems: `writing a custom storage system`_
  163. Storage objects
  164. ---------------
  165. Though most of the time you'll want to use a ``File`` object (which delegates to
  166. the proper storage for that file), you can use file storage systems directly.
  167. You can create an instance of some custom file storage class, or -- often more
  168. useful -- you can use the global default storage system::
  169. >>> from django.core.files.storage import default_storage
  170. >>> path = default_storage.save('/path/to/file', 'new content')
  171. >>> path
  172. u'/path/to/file'
  173. >>> default_storage.filesize(path)
  174. 11
  175. >>> default_storage.open(path).read()
  176. 'new content'
  177. >>> default_storage.delete(path)
  178. >>> default_storage.exists(path)
  179. False
  180. Storage objects define the following methods:
  181. ``Storage.exists(name)``
  182. ~~~~~~~~~~~~~~~~~~~~~~~~
  183. ``True`` if a file exists given some ``name``.
  184. ``Storage.path(name)``
  185. ~~~~~~~~~~~~~~~~~~~~~~
  186. The local filesystem path where the file can be opened using Python's standard
  187. ``open()``. For storage systems that aren't accessible from the local
  188. filesystem, this will raise ``NotImplementedError`` instead.
  189. ``Storage.size(name)``
  190. ~~~~~~~~~~~~~~~~~~~~~~
  191. Returns the total size, in bytes, of the file referenced by ``name``.
  192. ``Storage.url(name)``
  193. ~~~~~~~~~~~~~~~~~~~~~
  194. Returns the URL where the contents of the file referenced by ``name`` can be
  195. accessed.
  196. ``Storage.open(name, mode='rb')``
  197. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  198. Opens the file given by ``name``. Note that although the returned file is
  199. guaranteed to be a ``File`` object, it might actually be some subclass. In the
  200. case of remote file storage this means that reading/writing could be quite slow,
  201. so be warned.
  202. ``Storage.save(name, content)``
  203. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  204. Saves a new file using the storage system, preferably with the name specified.
  205. If there already exists a file with this name ``name``, the storage system may
  206. modify the filename as necessary to get a unique name. The actual name of the
  207. stored file will be returned.
  208. ``Storage.delete(name)``
  209. ~~~~~~~~~~~~~~~~~~~~~~~~
  210. Deletes the file referenced by ``name``. This method won't raise an exception if
  211. the file doesn't exist.
  212. Writing a custom storage system
  213. ===============================
  214. If you need to provide custom file storage -- a common example is storing files
  215. on some remote system -- you can do so by defining a custom storage class.
  216. You'll need to follow these steps:
  217. #. Your custom storage system must be a subclass of
  218. ``django.core.files.storage.Storage``::
  219. from django.core.files.storage import Storage
  220. class MyStorage(Storage):
  221. ...
  222. #. Django must be able to instantiate your storage system without any arguments.
  223. This means that any settings should be taken from ``django.conf.settings``::
  224. from django.conf import settings
  225. from django.core.files.storage import Storage
  226. class MyStorage(Storage):
  227. def __init__(self, option=None):
  228. if not option:
  229. option = settings.CUSTOM_STORAGE_OPTIONS
  230. ...
  231. #. Your storage class must implement the ``_open()`` and ``_save()`` methods,
  232. along with any other methods appropriate to your storage class. See below for
  233. more on these methods.
  234. In addition, if your class provides local file storage, it must override
  235. the ``path()`` method.
  236. Custom storage system methods
  237. -----------------------------
  238. Your custom storage system may override any of the storage methods explained
  239. above in `storage objects`_. However, it's usually better to use the hooks
  240. specifically designed for custom storage objects. These are:
  241. ``_open(name, mode='rb')``
  242. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  243. **Required**.
  244. Called by ``Storage.open()``, this is the actual mechanism the storage class
  245. uses to open the file. This must return a ``File`` object, though in most cases,
  246. you'll want to return some subclass here that implements logic specific to the
  247. backend storage system.
  248. ``_save(name, content)``
  249. ~~~~~~~~~~~~~~~~~~~~~~~~
  250. Called by ``Storage.save()``. The ``name`` will already have gone through
  251. ``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a
  252. ``File`` object itself. No return value is expected.
  253. ``get_valid_name(name)``
  254. ------------------------
  255. Returns a filename suitable for use with the underlying storage system. The
  256. ``name`` argument passed to this method is the original filename sent to the
  257. server, after having any path information removed. Override this to customize
  258. how non-standard characters are converted to safe filenames.
  259. The code provided on ``Storage`` retains only alpha-numeric characters, periods
  260. and underscores from the original filename, removing everything else.
  261. ``get_available_name(name)``
  262. ----------------------------
  263. Returns a filename that is available in the storage mechanism, possibly taking
  264. the provided filename into account. The ``name`` argument passed to this method
  265. will have already cleaned to a filename valid for the storage system, according
  266. to the ``get_valid_name()`` method described above.
  267. The code provided on ``Storage`` simply appends underscores to the filename
  268. until it finds one that's available in the destination directory.