我这几天一直在努力。使用S3与Django + django-storages和Heroku的静态文件。
首先,我创建一个S3存储桶 case 'SELECT_EDGE_OVERRIDE_IDX':
return {...state,selectedEdgeOverrideIdx: action.selectedEdgeOverrideIdx}
并生成访问密钥(访问密钥ID和秘密访问密钥)。
我安装了4f2xivbz443
https://django-storages.readthedocs.io/en/latest/,并按照有关如何添加和设置Amazon S3的说明进行操作。
当我部署时,我收到此错误:
django-storages
以下是所有代码。
settings.py(最后添加了Amazon S3设置)
raise error_class(parsed_response, operation_name)
botocore.exceptions.ClientError: An error occurred (InvalidRequest) when calling the PutObject operation: The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.
wsgi.py
import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "=ax=ka-emu33ivw-y^u00p8#uvop#-ag#+4pm_s4-=da^chbuk"
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# Disable Django's own staticfiles handling in favour of WhiteNoise, for
# greater consistency between gunicorn and `./manage.py runserver`. See:
# http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
'storages',
'images',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'helloworld.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
'debug': False,
},
},
]
WSGI_APPLICATION = 'helloworld.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# Allow all host headers
ALLOWED_HOSTS = ['*']
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Amazon S3
if not DEBUG:
SECRET_KEY = os.environ['SECRET_KEY']
AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = os.environ['AWS_STORAGE_BUCKET_NAME']
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
requirements.txt
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import DjangoWhiteNoise
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "helloworld.settings")
application = get_wsgi_application()
application = DjangoWhiteNoise(application)
图片/ models.py
boto==2.45.0
boto3==1.4.4
botocore==1.5.7
dj-database-url==0.4.1
Django==1.10.4
django-storages==1.5.2
docutils==0.13.1
gunicorn==19.6.0
jmespath==0.9.1
olefile==0.44
Pillow==4.0.0
psycopg2==2.6.2
python-dateutil==2.6.0
s3transfer==0.1.10
six==1.10.0
whitenoise==3.2
Heroku配置视频
from django.db import models
class ImageUpload(models.Model):
image = models.ImageField()
title = models.CharField(max_length=50, default=False)
def __str__(self):
return self.title
heroku构建日志
=== hidden-escarpment-87695 Config Vars
AWS_ACCESS_KEY_ID: <mys3key>
AWS_SECRET_ACCESS_KEY: <mysecretkey>
AWS_STORAGE_BUCKET_NAME: 4f2xivbz443
DATABASE_URL: postgres://wslatgvzefvimv:eebae0eeba511f1b8e8fe5c3c23a28740182dcfd7eb02138e8826c809a6967f1@ec2-176-34-186-178.eu-west-1.compute.amazonaws.com:5432/d21efhek9bf2u
7
SECRET_KEY: <myownsecretkey>
答案 0 :(得分:2)
Heroku:S3 / boto3-错误:
请使用AWS4-HMAC-SHA256, 对于在django-storages中面临AWS4-HMAC-SHA256错误(图像未加载)的人。
尝试在settings.py中使用此值:
如果使用boto3:
AWS_S3_REGION_NAME = 'us-east-2' #change to your region
AWS_S3_SIGNATURE_VERSION = 's3v4'
如果使用boto:
AWS_S3_HOST = 'us-east-2' #change to your region
S3_USE_SIGV4 = True
答案 1 :(得分:0)
使用WhiteNoise提供静态文件时,不应使用S3存储静态文件。 (使用S3存储和提供媒体文件很好 - 事实上,鼓励它。)
只需删除此行:
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
和这一行
STATIC_URL = 'http://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'
您可以保留其他设置。
如果您想将WhiteNoise与Cloudfront一起使用,则需要提供说明here。
P.S。在您的Heroku配置变量中,您已经发布了数据库凭据,因此任何人都可以连接到您的数据库。您可以重置here。