简体   繁体   English

无法使用Django从S3提供静态媒体

[英]Unable to serve static media from S3 with Django

I need to use Amazon S3 to serve my static and media files to my Django project. 我需要使用Amazon S3将我的静态和媒体文件提供给我的Django项目。

However, I am facing a lot of issues with that. 但是,我面临很多问题。 First, my code: 首先,我的代码:

s3utils.py

from storages.backends.s3boto import S3BotoStorage

class FixedS3BotoStorage(S3BotoStorage):
def url(self, name):
    url = super(FixedS3BotoStorage, self).url(name)
    if name.endswith('/') and not url.endswith('/'):
        url += '/'
    return url

StaticS3BotoStorage = lambda: FixedS3BotoStorage(location='static')
MediaS3BotoStorage = lambda: FixedS3BotoStorage(location='media')

In settings.py settings.py

DEFAULT_FILE_STORAGE = 'SpareGuru.s3utils.MediaS3BotoStorage'
STATICFILES_STORAGE = 'SpareGuru.s3utils.StaticS3BotoStorage'

AWS_HOST = "s3-ap-southeast-1.amazonaws.com"
AWS_ACCESS_KEY_ID = 'xx'
AWS_SECRET_ACCESS_KEY = 'yy'
AWS_STORAGE_BUCKET_NAME = 'zz'

S3_URL = 'http://%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
MEDIA_DIRECTORY = '/media/'
STATIC_DIRECTORY = '/static/'

STATIC_URL = "/static/"

MEDIA_URL = "/media/"

STATIC_ROOT = S3_URL + STATIC_DIRECTORY
COMPRESS_ROOT = STATIC_ROOT
MEDIA_ROOT = S3_URL + MEDIA_DIRECTORY

Here are the issues I face: 以下是我面临的问题:

  1. When running ./manage.py collectstatic , it starts to upload the files to S3 and after a couple of files, I get Broken Pipe error. 当运行./manage.py collectstatic ,它开始将文件上传到S3,在几个文件之后,我收到了Broken Pipe错误。

  2. When trying to run the webpage, I get the error: 'https://zz.s3.amazonaws.com/static/css/bootstrap.min.css?Signature=sign&Expires=1438359937&AWSAccessKeyId=xx' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed . 尝试运行网页时,出现错误: 'https://zz.s3.amazonaws.com/static/css/bootstrap.min.css?Signature=sign&Expires=1438359937&AWSAccessKeyId=xx' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed

No idea what's going on here. 不知道这里发生了什么。

Edit: My previous bucket policy allowed for Read only access. 编辑:我之前的存储桶策略允许只读访问。 So maybe that could have been the reason that my compressor was unable to create files on S3. 也许这可能是我的压缩器无法在S3上创建文件的原因。 I have updated the policy but still doesn't work. 我已更新政策但仍然无效。 Updated policy is: 更新的政策是:

{
"Statement": [
    {
        "Sid": "PublicReadForGetBucketObjects",
        "Effect": "Allow",
        "Principal": {
            "AWS": "*"
        },
        "Action": [
            "s3:GetObject"
        ],
        "Resource": [
            "arn:aws:s3:::zz/*"
        ]
    },
    {
        "Action": "s3:*",
        "Effect": "Allow",
        "Resource": [
            "arn:aws:s3:::zz",
            "arn:aws:s3:::zz/*"
        ],
        "Principal": {
            "AWS": [
                "my-arn:/goes=here"
            ]
        }
    }
]
}

And the CORS Configuration for my bucket is: 我的存储桶的CORS Configuration是:

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

I have this running on my own Django project. 我在自己的Django项目上运行。 I went and checked out the differences. 我去检查了差异。 One thing you might try is adding: 您可能尝试的一件事是添加:

AWS_QUERYSTRING_AUTH = False

to your settings.py. 到您的settings.py。 That could help with at least your issue #2. 至少在你的问题#2中,这可能会有所帮助。

Here's a full example from my settings.py. 这是我的settings.py的完整示例。 Note: I don't use S3 for static files, only media. 注意:我不使用S3作为静态文件,只使用媒体。

from boto.s3.connection import SubdomainCallingFormat
AWS_CALLING_FORMAT = SubdomainCallingFormat()
DEFAULT_FILE_STORAGE = 'project.s3utils.MediaRootS3BotoStorage'
AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID', None)
AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_KEY', None)
AWS_SECRET_KEY = os.getenv('AWS_SECRET_KEY')
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME')
AWS_QUERYSTRING_AUTH = False
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '../',  'static')
MEDIA_ROOT = os.path.join(BASE_DIR, '../..',  'media')
MEDIA_URL = 'http://{!s}.s3.amazonaws.com/media/'.format(AWS_STORAGE_BUCKET_NAME)

I believe your static and media urls/roots are incorrect. 我相信你的staticmedia网址/根是不正确的。 They should follow the format below: 他们应该遵循以下格式:

MEDIA_URL = S3_URL + MEDIA_DIRECTORY
STATIC_URL = S3_URL + STATIC_DIRECTORY
MEDIA_ROOT = '/home/host/app/static_root/media'
STATIC_ROOT = '/home/host/app/static_root/static'

Note: Change the MEDIA_ROOT and STATIC_ROOT to how your project is configured. 注意:将MEDIA_ROOTSTATIC_ROOT更改为项目的配置方式。

EDIT: 编辑:

Sorry, didn't see you were using compressor. 对不起,没看到你在使用压缩机。 Try doing the following: 尝试执行以下操作:

COMPRESS_URL = S3_URL + STATIC_DIRECTORY
STATIC_URL = COMPRESS_URL
MEDIA_URL = S3_URL + MEDIA_DIRECTORY
MEDIA_ROOT = '/home/host/app/static_root/media'
STATIC_ROOT = '/home/host/app/static_root/static'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM