custom-file-storage.txt 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. ===================================
  2. How to write a custom storage class
  3. ===================================
  4. .. currentmodule:: django.core.files.storage
  5. If you need to provide custom file storage -- a common example is storing files
  6. on some remote system -- you can do so by defining a custom storage class.
  7. You'll need to follow these steps:
  8. #. Your custom storage system must be a subclass of
  9. ``django.core.files.storage.Storage``::
  10. from django.core.files.storage import Storage
  11. class MyStorage(Storage):
  12. ...
  13. #. Django must be able to instantiate your storage system without any arguments.
  14. This means that any settings should be taken from ``django.conf.settings``::
  15. from django.conf import settings
  16. from django.core.files.storage import Storage
  17. class MyStorage(Storage):
  18. def __init__(self, option=None):
  19. if not option:
  20. option = settings.CUSTOM_STORAGE_OPTIONS
  21. ...
  22. #. Your storage class must implement the :meth:`_open()` and :meth:`_save()`
  23. methods, along with any other methods appropriate to your storage class. See
  24. below for more on these methods.
  25. In addition, if your class provides local file storage, it must override
  26. the ``path()`` method.
  27. #. Your storage class must be :ref:`deconstructible <custom-deconstruct-method>`
  28. so it can be serialized when it's used on a field in a migration. As long
  29. as your field has arguments that are themselves
  30. :ref:`serializable <migration-serializing>`, you can use the
  31. ``django.utils.deconstruct.deconstructible`` class decorator for this
  32. (that's what Django uses on FileSystemStorage).
  33. By default, the following methods raise ``NotImplementedError`` and will
  34. typically have to be overridden:
  35. * :meth:`Storage.delete`
  36. * :meth:`Storage.exists`
  37. * :meth:`Storage.listdir`
  38. * :meth:`Storage.size`
  39. * :meth:`Storage.url`
  40. Note however that not all these methods are required and may be deliberately
  41. omitted. As it happens, it is possible to leave each method unimplemented and
  42. still have a working Storage.
  43. By way of example, if listing the contents of certain storage backends turns
  44. out to be expensive, you might decide not to implement ``Storage.listdir()``.
  45. Another example would be a backend that only handles writing to files. In this
  46. case, you would not need to implement any of the above methods.
  47. Ultimately, which of these methods are implemented is up to you. Leaving some
  48. methods unimplemented will result in a partial (possibly broken) interface.
  49. You'll also usually want to use hooks specifically designed for custom storage
  50. objects. These are:
  51. .. method:: _open(name, mode='rb')
  52. **Required**.
  53. Called by ``Storage.open()``, this is the actual mechanism the storage class
  54. uses to open the file. This must return a ``File`` object, though in most cases,
  55. you'll want to return some subclass here that implements logic specific to the
  56. backend storage system. The :exc:`FileNotFoundError` exception should be raised
  57. when a file doesn't exist.
  58. .. method:: _save(name, content)
  59. Called by ``Storage.save()``. The ``name`` will already have gone through
  60. ``get_valid_name()`` and ``get_available_name()``, and the ``content`` will be a
  61. ``File`` object itself.
  62. Should return the actual name of name of the file saved (usually the ``name``
  63. passed in, but if the storage needs to change the file name return the new name
  64. instead).
  65. .. method:: get_valid_name(name)
  66. Returns a filename suitable for use with the underlying storage system. The
  67. ``name`` argument passed to this method is either the original filename sent to
  68. the server or, if ``upload_to`` is a callable, the filename returned by that
  69. method after any path information is removed. Override this to customize how
  70. non-standard characters are converted to safe filenames.
  71. The code provided on ``Storage`` retains only alpha-numeric characters, periods
  72. and underscores from the original filename, removing everything else.
  73. .. method:: get_alternative_name(file_root, file_ext)
  74. Returns an alternative filename based on the ``file_root`` and ``file_ext``
  75. parameters. By default, an underscore plus a random 7 character alphanumeric
  76. string is appended to the filename before the extension.
  77. .. method:: get_available_name(name, max_length=None)
  78. Returns a filename that is available in the storage mechanism, possibly taking
  79. the provided filename into account. The ``name`` argument passed to this method
  80. will have already cleaned to a filename valid for the storage system, according
  81. to the ``get_valid_name()`` method described above.
  82. The length of the filename will not exceed ``max_length``, if provided. If a
  83. free unique filename cannot be found, a :exc:`SuspiciousFileOperation
  84. <django.core.exceptions.SuspiciousOperation>` exception is raised.
  85. If a file with ``name`` already exists, ``get_alternative_name()`` is called to
  86. obtain an alternative name.
  87. .. _using-custom-storage-engine:
  88. Use your custom storage engine
  89. ==============================
  90. .. versionadded:: 4.2
  91. The first step to using your custom storage with Django is to tell Django about
  92. the file storage backend you'll be using. This is done using the
  93. :setting:`STORAGES` setting. This setting maps storage aliases, which are a way
  94. to refer to a specific storage throughout Django, to a dictionary of settings
  95. for that specific storage backend. The settings in the inner dictionaries are
  96. described fully in the :setting:`STORAGES` documentation.
  97. Storages are then accessed by alias from from the
  98. :data:`django.core.files.storage.storages` dictionary::
  99. from django.core.files.storage import storages
  100. example_storage = storages["example"]