如何使用 django-storages 和 Amazon S3 设置 Django 项目,但使用不同的文件夹来存放静态文件和媒体文件? [英] How to set-up a Django project with django-storages and Amazon S3, but with different folders for static files and media files?
问题描述
我正在配置一个 Django 项目,该项目使用服务器文件系统来存储应用程序静态文件 (STATIC_ROOT
) 和用户上传的文件 (MEDIA_ROOT
).
I'm configuring a Django project that were using the server filesystem for storing the apps static files (STATIC_ROOT
) and user uploaded files (MEDIA_ROOT
).
我现在需要在 Amazon 的 S3 上托管所有这些内容,因此我为此创建了一个存储桶.使用 django-storages
和 boto
存储后端,我设法将收集的静态数据上传到 S3 存储桶:
I need now to host all that content on Amazon's S3, so I have created a bucket for this. Using django-storages
with the boto
storage backend, I managed to upload collected statics to the S3 bucket:
MEDIA_ROOT = '/media/'
STATIC_ROOT = '/static/'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = 'KEY_ID...'
AWS_SECRET_ACCESS_KEY = 'ACCESS_KEY...'
AWS_STORAGE_BUCKET_NAME = 'bucket-name'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
然后,我遇到了一个问题:MEDIA_ROOT
和 STATIC_ROOT
未在存储桶中使用,因此存储桶根目录包含静态文件和用户上传的路径.
Then, I got a problem: the MEDIA_ROOT
and STATIC_ROOT
are not used within the bucket, so the bucket root contains both the static files and user uploaded paths.
然后我可以设置:
S3_URL = 'http://s3.amazonaws.com/%s' % AWS_STORAGE_BUCKET_NAME
STATIC_URL = S3_URL + STATIC_ROOT
MEDIA_URL = 'S3_URL + MEDIA_ROOT
并在模板中使用这些设置,但是在使用 django-storages
存储在 S3 中时,静态/媒体文件没有区别.
And use those settings in the templates, but there is no distinction of static/media files when storing in S3 with django-storages
.
如何做到这一点?
谢谢!
推荐答案
我认为以下应该可行,并且比 Mandx 的方法更简单,尽管它非常相似:
I think the following should work, and be simpler than Mandx's method, although it's very similar:
创建一个 s3utils.py
文件:
from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media')
然后在您的 settings.py
中:
DEFAULT_FILE_STORAGE = 'myproject.s3utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'myproject.s3utils.StaticRootS3BotoStorage'
在两个 example_
文件 这里.
这篇关于如何使用 django-storages 和 Amazon S3 设置 Django 项目,但使用不同的文件夹来存放静态文件和媒体文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!