在AWS S3上设置媒体文件访问 [英] Setting up media file access on AWS S3

查看:85
本文介绍了在AWS S3上设置媒体文件访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 boto3 django-storage 库来加载django项目的媒体文件.

Im using boto3 and django-storage libraries for apload media files of my django project.

storage_backends.py

 class PrivateMediaStorage(S3Boto3Storage):
    location = settings.AWS_STORAGE_LOCATION
    default_acl = 'private'
    file_overwrite = False
    custom_domain = False

class PublicStaticStorage(S3Boto3Storage):
    location = settings.AWS_PUBLIC_STATIC_LOCATION

settings.py

AWS_STORAGE_LOCATION = 'media/private'
AWS_LOCATION = 'static'
AWS_PUBLIC_STATIC_LOCATION = 'static/'
DEFAULT_FILE_STORAGE = 'path.to.PrivateMediaStorage'

models.py

models.py

class Documents(models.Model):
    """ uploaded documents"""

    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    upload = models.FileField(storage=PrivateMediaStorage())
    filename = models.CharField(_('documents name'), max_length=255, blank=True, null=True)
    datafile = models.FileField()
    created = models.DateTimeField(auto_now_add=True)
    type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True)

文件加载效果很好.但是有一点我不理解,指向文件的链接看起来错误(它包含静态而不是媒体).看起来像

File loading works well. But there is a point I don't understand, and the link to the file looks wrong (it contains static instead of media). Looks like

https://myhost.s3.amazonaws.com/static/class-descriptions_1.csv

还有其他有关访问的信息.现在,我单击文件的链接,我会收到一条消息

And else about access. Now that I click on the link to the file, I get a message

<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>4B8296F8F77491F5</RequestId>
<HostId>
CG96q+LGWcvsIK2YkuaE2wExL8/YTqH1PmjOSFGAqcgaKaTYnOet1QoItGJhW1Oj
</HostId>
</Error>

这对于未注册用户来说是正常的,但是如何允许在Django项目中注册的用户看到此文件?

This is normal for unregistered users, but how do I allow users registered in my Django project to see this file?

推荐答案

您必须使用预签名的URL来实现此功能.如果存储桶是公共的,则所有用户都可以访问S3对象.如果要限制访问,则存储桶必须是私有的,并且需要为每个用户生成预签名的URL.

You have to use pre-signed URLs to implement this functionality. All users can access S3 objects if the bucket is public. If you want to restrict access, then the bucket has to be private and you need to generate pre-signed URLs per user.

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-presigned-urls.html

这篇关于在AWS S3上设置媒体文件访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆