假設(shè)已經(jīng)有S3的bucket存儲(chǔ)
安裝依賴module
$ pip install django-storages boto
配置Django
static靜態(tài)文件和media多媒體(多為用戶上傳)需要分目錄存儲(chǔ)未蝌,新建s3utils.py文件:
from storages.backends.s3boto import S3BotoStorage
StaticS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaS3BotoStorage = lambda: S3BotoStorage(location='media')
settings.py添加S3配置:
AWS_STORAGE_BUCKET_NAME = 'horoscope-cxclient'
DEFAULT_FILE_STORAGE = 'horoscope_web.src.s3utils.MediaS3BotoStorage'
STATICFILES_STORAGE = 'horoscope_web.src.s3utils.StaticS3BotoStorage'S3_URL = 'http://%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
STATIC_DIRECTORY = '/static/'
MEDIA_DIRECTORY = '/media/'
STATIC_URL = S3_URL + STATIC_DIRECTORY
MEDIA_URL = S3_URL + MEDIA_DIRECTORY
因?yàn)镾3開放了本機(jī)訪問權(quán)限洪己,因?yàn)椴恍枰J(rèn)證话速。
需要認(rèn)證的添加 KEY_ID 和ACCESS_KEY:
AWS_ACCESS_KEY_ID = 'YOURACCESSKEY'
AWS_SECRET_ACCESS_KEY = 'YOURSECRETACCESSKEY'
部署
運(yùn)行collectstaticDjango管理命令
:
靜態(tài)文件應(yīng)該以http://horoscope-cxclient.s3.amazonaws.com/static/為結(jié)尾注服。
任何上傳的文件FileField或ImageField模型上的屬性都應(yīng)該在http://horoscope-cxclient.s3.amazonaws.com/media/中。如果這些模型屬性指定upload_to路徑,則存儲(chǔ)于/media/***
。
CDN配置
如上配置配置成功后诱渤,資源訪問域名是https://horoscope-cxclient.s3.amazonaws.com/media/
https://horoscope-cxclient.s3.amazonaws.com/media/fortunes_wci_img/wci_c013086e41c4e4159dc42b6b0448b6c8.png
發(fā)現(xiàn)資源加載速度慢了很多,17K耗時(shí)將近兩秒谈况,而且不同區(qū)域訪問不穩(wěn)定。
此時(shí)就應(yīng)該祭出CDN了 知乎CDN
CDN HOST:http://***.cloudfront.net/
递胧,解析至http://static.mobileapp666.com
域名下碑韵,settings配置:
AWS_S3_SECURE_URLS = False
#AWS_S3_USE_SSL = False
AWS_S3_CALLING_FORMAT = 'boto.s3.connection.OrdinaryCallingFormat'
AWS_S3_CUSTOM_DOMAIN = 'static.mobileapp666.com'
重啟后資源通過http://static.mobileapp666.com/**
訪問,速度有了明顯的提高缎脾。
AWS_S3_SECURE_URLS: 是否啟動(dòng)安全網(wǎng)址祝闻,即是否使用https, 默認(rèn)為True遗菠,因?yàn)閔ttps需要申請(qǐng)證書等等一系列處理联喘,暫時(shí)設(shè)置為False后將使用http協(xié)議。
使用 staticfiles
The one from staticfiles ({% load static from staticfiles %}) is smarter - it uses whatever storage class you've configured for static files to come up with the URL.
By using the one from staticfiles from the start, you'll be prepared for any storage class you might decide to use in the future.
常用命令:
查看
aws s3 ls s3://bucketname/
aws s3 ls s3://bucketname/dir_name
上傳
單個(gè)文件
aws s3 cp 目標(biāo)文件 上傳路徑
aws s3 cp source_file s3://bucktename/dir_name
上傳目錄 需要添加參數(shù) --recursive
aws s3 cp source_file s3://bucktename/dir_name --recursive
AWS CLI命令參考:AWS CLI Command Reference
參考:
cname-support-aws_s3_custom_domain-doesnt
django-wont-serve-static-files-from-amazon-s3-with-custom-domain
Using-Amazon-S3-to-store-your-Django-sites-static-and-media-files