简体   繁体   中英

Setting Django to serve media files from Amazon S3

I'm trying to deploy my project in Heroku but the media files (images) are deleted after a while, so someone told me that i need to use a service called "Amazon S3", my question is, how to configure my prject to use that service. Can somebody help me?

Check out this for starters http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteHosting.html

Basically you don't need Django to serve anything here, instead you need to make sure the static references point to another domain (the S3 one) instead of your Heroku one.

You could follow the steps in this article:

http://blog.doismellburning.co.uk/2012/07/14/using-amazon-s3-to-host-your-django-static-files/

But a little tutorial to do that could be:

Step 1 - Install boto and django-storages:

$ pip install boto django-storages

Add django-storages to INSTALLED_APPS:

INSTALLED_APPS += ('storages',)

Step 2 - Create your S3 bucket:

Go to https://console.aws.amazon.com/s3/home and create it.

Step 3 - Get your credentials:

Go to https://console.aws.amazon.com/iam/home?#security_credential , click on "Access Keys" and create it.

Step 4 - Add your credentials to django settings:

First of all, create a file called s3utils.py in the project folder, with the follow content:

from storages.backends.s3boto import S3BotoStorage                                            
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')              
MediaRootS3BotoStorage  = lambda: S3BotoStorage(location='media') 

I prefer to use all of this configurations as environment variables, so I suggest you to do:

$ heroku config:set AWS_ACCESS_KEY_ID=YOUR_ACCESS_KEY AWS_SECRET_ACCESS_KEY=YOUR_SECRET_ACCESS_KEY S3_BUCKET_NAME=YOUR_BUCKET_NAME

And after that, put this in your settings:

AWS_STORAGE_BUCKET_NAME = os.environ['S3_BUCKET_NAME']                          
MEDIA_ROOT = '/media/'                                                          
S3_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME                
MEDIA_URL = S3_URL + MEDIA_ROOT                                                 
DEFAULT_FILE_STORAGE = 'YOUR_PROJECT.s3utils.MediaRootS3BotoStorage'                 
STATICFILES_STORAGE = 'YOUR_PROJECT.s3utils.StaticRootS3BotoStorage'                 
AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']                             
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']  

Step 5 - Run collectstatic again

You'll need collect static files again, so that it will be put in Amazon.

heroku run python manage.py collectstatic

I hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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