AWS S3 Bucket Django 3.0 用户配置文件图像上传访问错误
AWS S3 Bucket Django 3.0 User Profile Image Upload Access ERROR
简介
- 我正在关注 this guide as recommended, here is the guide's GitHub repo。
- 我也为它创建了 AmazonS3FullAccess
- 我正在使用指南的第 3 个示例“混合 public 资产和私人资产”与静态、媒体 public、媒体、私人版本。
- 如果用户登录(本地开发环境),他会从网站上传文件,但他只能从 AWS S3 管理网站访问这些文件。
- 目前我正在阻止所有 public 指南中的访问(AWS S3 管理面板设置)
- 我已将这些行添加到我的 CORS 配置编辑器 来自 this other guide
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
- 切换到对我来说更本地的中央欧盟服务器。不工作我得到了同样的错误。
storage_backends.py
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = settings.AWS_STATIC_LOCATION
class PublicMediaStorage(S3Boto3Storage):
location = settings.AWS_PUBLIC_MEDIA_LOCATION
file_overwrite = False
class PrivateMediaStorage(S3Boto3Storage):
location = settings.AWS_PRIVATE_MEDIA_LOCATION
default_acl = 'private'
file_overwrite = False
custom_domain = False
settings.py
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'MYPROJECTS_MAIN_APP/static'),]
AWS_ACCESS_KEY_ID = 'DSHUGASGHLASF678FSHAFH'
AWS_SECRET_ACCESS_KEY = 'uhsdgahsfgskajgjkafgjkdfjkgkjdfgfg'
AWS_STORAGE_BUCKET_NAME = 'MYSTORAGE289377923'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_STATIC_LOCATION = 'static'
STATICFILES_STORAGE = 'mysite.storage_backends.StaticStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
AWS_PUBLIC_MEDIA_LOCATION = 'media/public'
DEFAULT_FILE_STORAGE = 'mysite.storage_backends.PublicMediaStorage'
AWS_PRIVATE_MEDIA_LOCATION = 'media/private'
PRIVATE_FILE_STORAGE = 'mysite.storage_backends.PrivateMediaStorage'
AWS_S3_HOST = "s3.eu-central-1.amazonaws.com"
S3_USE_SIGV4 = True
AWS_S3_REGION_NAME = "eu-central-1"
models.py
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from mysite.storage_backends import PrivateMediaStorage
class Document(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
upload = models.FileField()
class PrivateDocument(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
upload = models.FileField(storage=PrivateMediaStorage())
user = models.ForeignKey(User, related_name='documents')
views.py
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from .models import Document, PrivateDocument
class DocumentCreateView(CreateView):
model = Document
fields = ['upload', ]
success_url = reverse_lazy('home')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
documents = Document.objects.all()
context['documents'] = documents
return context
@method_decorator(login_required, name='dispatch')
class PrivateDocumentCreateView(CreateView):
model = PrivateDocument
fields = ['upload', ]
success_url = reverse_lazy('profile')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
错误
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>56fg67dfg56df7g67df</RequestId>
<HostId>
hsiugYIGYfhuieHF7weg68g678dsgds78g67dsg86sdg68ds7g68ds7yfsd8f8hd7
</HostId>
</Error>
到目前为止我已经尝试过的事情
- 中间有一段时间它创建了 AWS link 并将文件添加到本地 "media" 文件夹。但是因为我已经删除了 "Media folder" 并且它只创建 URL links,并且实际上将它们上传到 S3 存储桶
- 我在 aws 论坛上找到了相同的 question 但尚未得到答复
- 访问权限 Django + AWS S3 Bucket: Authenticated Access to S3 Bucket (I don't understand this answer )
- "use AWS4-HMAC-SHA256"
- 指定 S3 主机的区域以正确使用 https://github.com/aws/aws-sdk-js/issues/829
- 查找您所在地区的站点 - https://docs.aws.amazon.com/general/latest/gr/rande.html
- 我也收到了这个推荐 "Most new regions only support
AWS4-HMAC-SHA256
- if your code doesn't support this authentication scheme and only created "v2 signatures 在旧地区之一创建你的 bucket,例如在欧洲似乎只有 爱尔兰 - 在这里查看:https://docs.aws.amazon.com/general/latest/gr/signature-version-2.html"
- 我在欧盟使用我的测试机器 - 我设置了一个美国基础 S3 存储桶 - 我如何配置 Django 应用程序或 AWS S3 存储桶以便它将允许从任何地方访问它(特别重要的是,该应用程序的部署使得世界各地的人们都可以访问它)。来自同一个 video's 评论区的人评论了以下内容
Steve D
Great video series, just to say I am using an S3 bucket in Europe and needed to add additional settings AWS_S3_HOST = "s3.eu-west-2.amazonaws.com" and AWS_S3_REGION_NAME="eu-west-2" to make it work
- 这是我在设置 based on 中添加的确切代码,并且是对原始指南代码的补充。当我切换图像时它可以工作但是当我离开配置文件设置并返回时图像消失并给出原始错误):
AWS_S3_HOST = "s3.eu-central-1.amazonaws.com"
S3_USE_SIGV4 = True
AWS_S3_REGION_NAME = "eu-central-1"
- 关闭所有访问限制(暂时)并将存储桶策略添加到 AWS S3 管理控制台
- 1 代码:
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "", "Action":["s3:GetObject"], "Resource":["arn:aws:s3:::myprojectname_that_jsut_abow_this_field/*" ] } ] }
--> 错误
- 2 代码:
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "", "Action":["s3:GetObject"], "Resource":["arn:aws:s3:::myprojectname_that_jsut_abow_this_field/" ] } ] }/*
--> 错误
- 3 CODE: 我改成了这个
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "*", "Action":["s3:GetObject"], "Resource":"arn:aws:s3:::myprojectname_that_jsut_abow_this_field/*" } ] }
并得到以下错误:Error Access denied
- 4 代码:
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "", "Action":["s3:GetObject"], "Resource":"arn:aws:s3:::myprojectname_that_jsut_abow_this_field/*" } ] }
错误:
Error Missing required field Principal cannot be empty!
在 AWS 控制台中,单击 "Permissions" 选项卡,然后单击
- 允许 public 访问您的存储桶 -> 保存 -> 确认
- "Bucket policy" 按钮。将出现一个编辑框。将编辑框中的 "arn:aws:s3:::" 替换为您编辑框上方显示的以 "arn:" 开头的部分,但注意保留其末尾的“/*”。使用下面的代码。粘贴以下内容:
{
"Version":"2012-10-17",
"Statement":[{
"Sid":"PublicReadGetObject",
"Effect":"Allow",
"Principal": "*",
"Action":["s3:GetObject"],
"Resource":["arn:aws:s3:::your-buckt-arn/*"
]
}
]
}
不确定您是否仍在尝试这个问题。
您可以尝试添加一个参数:
AWS_DEFAULT_ACL = 'public-read' 在你的 setting.py
删除您存储桶中所有之前上传的文件。
重新上传媒体和静态文件。
看看是否有效。
简介
- 我正在关注 this guide as recommended, here is the guide's GitHub repo。
- 我也为它创建了 AmazonS3FullAccess
- 我正在使用指南的第 3 个示例“混合 public 资产和私人资产”与静态、媒体 public、媒体、私人版本。
- 如果用户登录(本地开发环境),他会从网站上传文件,但他只能从 AWS S3 管理网站访问这些文件。
- 目前我正在阻止所有 public 指南中的访问(AWS S3 管理面板设置)
- 我已将这些行添加到我的 CORS 配置编辑器 来自 this other guide
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
- 切换到对我来说更本地的中央欧盟服务器。不工作我得到了同样的错误。
storage_backends.py
from django.conf import settings
from storages.backends.s3boto3 import S3Boto3Storage
class StaticStorage(S3Boto3Storage):
location = settings.AWS_STATIC_LOCATION
class PublicMediaStorage(S3Boto3Storage):
location = settings.AWS_PUBLIC_MEDIA_LOCATION
file_overwrite = False
class PrivateMediaStorage(S3Boto3Storage):
location = settings.AWS_PRIVATE_MEDIA_LOCATION
default_acl = 'private'
file_overwrite = False
custom_domain = False
settings.py
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'MYPROJECTS_MAIN_APP/static'),]
AWS_ACCESS_KEY_ID = 'DSHUGASGHLASF678FSHAFH'
AWS_SECRET_ACCESS_KEY = 'uhsdgahsfgskajgjkafgjkdfjkgkjdfgfg'
AWS_STORAGE_BUCKET_NAME = 'MYSTORAGE289377923'
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_STATIC_LOCATION = 'static'
STATICFILES_STORAGE = 'mysite.storage_backends.StaticStorage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_STATIC_LOCATION)
AWS_PUBLIC_MEDIA_LOCATION = 'media/public'
DEFAULT_FILE_STORAGE = 'mysite.storage_backends.PublicMediaStorage'
AWS_PRIVATE_MEDIA_LOCATION = 'media/private'
PRIVATE_FILE_STORAGE = 'mysite.storage_backends.PrivateMediaStorage'
AWS_S3_HOST = "s3.eu-central-1.amazonaws.com"
S3_USE_SIGV4 = True
AWS_S3_REGION_NAME = "eu-central-1"
models.py
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from mysite.storage_backends import PrivateMediaStorage
class Document(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
upload = models.FileField()
class PrivateDocument(models.Model):
uploaded_at = models.DateTimeField(auto_now_add=True)
upload = models.FileField(storage=PrivateMediaStorage())
user = models.ForeignKey(User, related_name='documents')
views.py
from django.contrib.auth.decorators import login_required
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from .models import Document, PrivateDocument
class DocumentCreateView(CreateView):
model = Document
fields = ['upload', ]
success_url = reverse_lazy('home')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
documents = Document.objects.all()
context['documents'] = documents
return context
@method_decorator(login_required, name='dispatch')
class PrivateDocumentCreateView(CreateView):
model = PrivateDocument
fields = ['upload', ]
success_url = reverse_lazy('profile')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
错误
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>56fg67dfg56df7g67df</RequestId>
<HostId>
hsiugYIGYfhuieHF7weg68g678dsgds78g67dsg86sdg68ds7g68ds7yfsd8f8hd7
</HostId>
</Error>
到目前为止我已经尝试过的事情
- 中间有一段时间它创建了 AWS link 并将文件添加到本地 "media" 文件夹。但是因为我已经删除了 "Media folder" 并且它只创建 URL links,并且实际上将它们上传到 S3 存储桶
- 我在 aws 论坛上找到了相同的 question 但尚未得到答复
- 访问权限 Django + AWS S3 Bucket: Authenticated Access to S3 Bucket (I don't understand this answer )
- "use AWS4-HMAC-SHA256"
- 指定 S3 主机的区域以正确使用 https://github.com/aws/aws-sdk-js/issues/829
- 查找您所在地区的站点 - https://docs.aws.amazon.com/general/latest/gr/rande.html
- 我也收到了这个推荐 "Most new regions only support
AWS4-HMAC-SHA256
- if your code doesn't support this authentication scheme and only created "v2 signatures 在旧地区之一创建你的 bucket,例如在欧洲似乎只有 爱尔兰 - 在这里查看:https://docs.aws.amazon.com/general/latest/gr/signature-version-2.html" - 我在欧盟使用我的测试机器 - 我设置了一个美国基础 S3 存储桶 - 我如何配置 Django 应用程序或 AWS S3 存储桶以便它将允许从任何地方访问它(特别重要的是,该应用程序的部署使得世界各地的人们都可以访问它)。来自同一个 video's 评论区的人评论了以下内容
Steve D Great video series, just to say I am using an S3 bucket in Europe and needed to add additional settings AWS_S3_HOST = "s3.eu-west-2.amazonaws.com" and AWS_S3_REGION_NAME="eu-west-2" to make it work
- 这是我在设置 based on 中添加的确切代码,并且是对原始指南代码的补充。当我切换图像时它可以工作但是当我离开配置文件设置并返回时图像消失并给出原始错误):
AWS_S3_HOST = "s3.eu-central-1.amazonaws.com"
S3_USE_SIGV4 = True
AWS_S3_REGION_NAME = "eu-central-1"
- 关闭所有访问限制(暂时)并将存储桶策略添加到 AWS S3 管理控制台
- 1 代码:
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "", "Action":["s3:GetObject"], "Resource":["arn:aws:s3:::myprojectname_that_jsut_abow_this_field/*" ] } ] }
--> 错误 - 2 代码:
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "", "Action":["s3:GetObject"], "Resource":["arn:aws:s3:::myprojectname_that_jsut_abow_this_field/" ] } ] }/*
--> 错误 - 3 CODE: 我改成了这个
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "*", "Action":["s3:GetObject"], "Resource":"arn:aws:s3:::myprojectname_that_jsut_abow_this_field/*" } ] }
并得到以下错误:Error Access denied
- 4 代码:
{ "Version":"2012-10-17", "Statement":[{ "Sid":"PublicReadGetObject", "Effect":"Allow", "Principal": "", "Action":["s3:GetObject"], "Resource":"arn:aws:s3:::myprojectname_that_jsut_abow_this_field/*" } ] }
错误:Error Missing required field Principal cannot be empty!
- 1 代码:
在 AWS 控制台中,单击 "Permissions" 选项卡,然后单击
- 允许 public 访问您的存储桶 -> 保存 -> 确认
- "Bucket policy" 按钮。将出现一个编辑框。将编辑框中的 "arn:aws:s3:::" 替换为您编辑框上方显示的以 "arn:" 开头的部分,但注意保留其末尾的“/*”。使用下面的代码。粘贴以下内容:
{
"Version":"2012-10-17",
"Statement":[{
"Sid":"PublicReadGetObject",
"Effect":"Allow",
"Principal": "*",
"Action":["s3:GetObject"],
"Resource":["arn:aws:s3:::your-buckt-arn/*"
]
}
]
}
不确定您是否仍在尝试这个问题。
您可以尝试添加一个参数: AWS_DEFAULT_ACL = 'public-read' 在你的 setting.py
删除您存储桶中所有之前上传的文件。
重新上传媒体和静态文件。
看看是否有效。