<p>这听起来有点棘手,那就是在一个项目中同时拥有<em>公共</em>和<em>私有</em>媒体存储。在</p>
<p>下面的示例假设您使用的是<a href="https://django-storages.readthedocs.io/en/latest/" rel="nofollow noreferrer">django storages</a>,但是不管怎样,该技术都应该起作用。在</p>
<p>通过扩展<code>S3BotoStorage</code>类来定义私有存储。在</p>
<p>如果使用S3,最好将<em>private</em>和<em>public</em>public存储在不同的S3存储桶中。此自定义存储允许您通过设置指定此参数。在</p>
<pre><code># yourapp.custom_storage.py
from django.conf import settings
from django.core.files.storage import get_storage_class
from storages.backends.s3boto import S3BotoStorage
class S3PrivateStorage(S3BotoStorage):
"""
Optional
"""
default_acl = "private" # this does the trick
def __init__(self):
super(S3PrivateStorage, self).__init__()
self.bucket_name = settings.S3_PRIVATE_STORAGE_BUCKET_NAME
# important
private_storage_class = get_storage_class(settings.PRIVATE_FILE_STORAGE)
private_storage = private_storage_class() # instantiate the storage
</code></pre>
<p>重要的部分是这个文件的最后2行-它声明了<code>private_storage</code>,以便在您的<code>FileField</code>中使用:</p>
^{pr2}$
<p>最后,在您的设置文件中,应该这样做。在</p>
<pre><code># settings.py
if DEBUG:
# In debug mode, store everything on the filestystem
DEFAULT_FILE_STORAGE = 'django.files.storage.FileSystemStorage'
PRIVATE_FILE_STORAGE = 'django.files.storage.FileSystemStorage'
else:
# In production store public things using S3BotoStorage and private things
# in a custom storage
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
PRIVATE_FILE_STORAGE = 'yourapp.custom_storage.S3PrivateStorage'
</code></pre>
<p>最后一条不请自来的建议是:将存储设置从<em>调试模式</em>中分离出来,并允许在环境变量中指定上述所有参数,这通常很有用。在某些时候,您可能希望使用类似生产的存储配置在调试模式下运行应用程序。在</p>