Django静态文件URL已损坏

时间:2014-04-16 01:02:35

标签: python django heroku amazon-s3 boto

我正在使用Boto2帮助在heroku上与我的Django-admin应用程序进行s3集成。我的静态文件生成的某些网址不正确。 例如:

https://BUCKET.s3.amazonaws.com/FOLDER/static/admin?Signature=XXX&Expires=YYY&AWSAccessKeyId=ZZZimg/icon_calendar.gif

什么时候应该

https://BUCKET.s3.amazonaws.com/FOLDER/static/admin/img/icon_calendar.gif?Signature=XXX&Expires=YYY&AWSAccessKeyId=ZZZ

请注意img/icon_calendar.gif不合适。我能想到的唯一导致这个问题的是我用来在我的存储桶中的子文件夹上创建静态文件的代码。它基于this SO solution

#s3utils.py
from storages.backends.s3boto import S3BotoStorage
import  os

STATIC_ROOT = 'FOLDER/static'
MEDIA_ROOT = 'FOLDER/media'

StaticRootS3BotoStorage = lambda: S3BotoStorage(location=STATIC_ROOT)
MediaRootS3BotoStorage  = lambda: S3BotoStorage(location=MEDIA_ROOT)

#settings.py
...
AWS_STORAGE_BUCKET_NAME = "BUCKET"
AWS_ACCESS_KEY_ID = 'ZZZ'
AWS_SECRET_ACCESS_KEY = 'AAAA'
DEFAULT_FILE_STORAGE = 'app.s3utils.MediaRootS3BotoStorage'
STATICFILES_STORAGE = 'app.s3utils.StaticRootS3BotoStorage'

S3_URL = 'http://%s.s3.amazonaws.com/' % (AWS_STORAGE_BUCKET_NAME)

STATIC_ROOT = '/FOLDER/static/'
MEDIA_ROOT = '/FOLDER/media/'

STATIC_URL = '%sFOLDER/static/' % (S3_URL)
MEDIA_URL = '%sFOLDER/media/' % (S3_URL)

什么可能导致网址损坏?

2 个答案:

答案 0 :(得分:1)

我在git repo找到了一个修复程序。我的s3utils.py文件现在看起来像

#s3utils.py
from storages.backends.s3boto import S3BotoStorage
import  os

STATIC_ROOT = 'FOLDER/static'
MEDIA_ROOT = 'FOLDER/media'

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

StaticRootS3BotoStorage = lambda: FixedS3BotoStorage(location=STATIC_ROOT)
MediaRootS3BotoStorage  = lambda: FixedS3BotoStorage(location=MEDIA_ROOT)

答案 1 :(得分:0)

AWS_QUERYSTRING_AUTH = False
AWS_ACCESS_KEY_ID = os.environ.get('your_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('your_key')
AWS_STORAGE_BUCKET_NAME = 'yourbucketname'
AWS_PRELOAD_METADATA = True #helps collectstatic do updates

STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/bucket/folder/static'

MEDIA_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/ bucket/folder/media'