2
0

custom-file-storage.txt 5.5 KB

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