Question

I am using Boto2 to help with s3 integration with my Django-admin app on heroku. Some of the urls are being generated incorrectly for my static files. Example:

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

When it should be

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

Notice that img/icon_calendar.gif is out of place. The only thing I can think that is causing this issue is the code I used to make the static files on a sub folder in my bucket. It is based on 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)

What could be causing the URLs to get corrupted?

Was it helpful?

Solution

I found a fix in this git repo. My s3utils.py file now looks like

#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)

OTHER TIPS

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top