Serving Django's static and media files from S3

冷暖自知 提交于 2019-12-07 03:06:20

问题


I'm having a weird problem and I have no idea what's causing it. Here's my current config (using Heroku):

MEDIA_URL = '/media/'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, '../static'),
)

#Determine if local or deployed.
if 'DATABASE_URL' in os.environ:
    STATICFILES_STORAGE     = 'storages.backends.s3boto.S3BotoStorage'
    AWS_ACCESS_KEY_ID       = 'A...A' 
    AWS_SECRET_ACCESS_KEY   = '...R' 
    DEFAULT_FILE_STORAGE    = 'storages.backends.s3boto.S3BotoStorage'

    # PRODUCTION OR STAGING
    if 'PROD' in os.environ:
        AWS_STORAGE_BUCKET_NAME = 's3.project.com'
        STATIC_URL = "https://s3.amazonaws.com/project/"
    else:
        AWS_STORAGE_BUCKET_NAME = 'project-staging'
        STATIC_URL = "https://s3.amazonaws.com/project-staging/"
else:
    STATIC_ROOT = ''

The thing is, static files are working fine, the links look like this: https://s3.amazonaws.com/project-staging/img/homepage_left.png.

First problem (Admin half broken):

The admin is half working. CSS files are served fine: https://project-staging.s3.amazonaws.com/admin/js/core.js?Signature=asdasdasd%3D&Expires=1352430664&AWSAccessKeyId=asdasdasA but the all the images are broken:

https://project-staging.s3.amazonaws.com/admin?Signature=%2asdasdad%3D&Expires=1352430664&AWSAccessKeyId=asdasdaimg/icon_calendar.gif

I don't know why the Signature and AWSAccesskey are there :(. If I remove them (by hand) the URL works fine!

Second problem (uploaded media via ImageField/FileField):

I'm using {{MEDIA_URL}}{{object.flyer}}, it translates to /media/media/flyers/poster_1.png, how do I point it out to s3? It should be like this: https://project-staging.s3.amazonaws.com/media/flyers/poster_1.png


回答1:


Answer to your second question: you need to set MEDIA_URL = https://project-staging.s3.amazonaws.com/media/ just like you're doing for STATIC_URL




回答2:


For your first question, I think you need to do:

AWS_QUERYSTRING_AUTH = False



回答3:


Adding the answers:

First problem: Make sure your bucket is set to public and set AWS_QUERYSTRING_AUTH in your settings to False, that way your file will be served without the signature part

AWS_QUERYSTRING_AUTH = False

Second problem: Make sure you add "url" at the end {{..url}}

{{MEDIA_URL}}{{object.flyer.url}}


来源:https://stackoverflow.com/questions/13301200/serving-djangos-static-and-media-files-from-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!