将文件保存在S3子文件夹中

时间:2018-11-23 07:53:27

标签: python django amazon-s3

如果我没记错的话,S3中没有真正的文件夹。但是似乎可以使用path来保存文件,因此它看起来像一个文件夹(在AWS控制台中导航时,这些文件夹甚至都可见)。

在Django中有一个FileField,我该如何在其中添加一个文件夹名称?

例如下面的方法有效,但是被放在根存储桶中,该存储桶变得非常混乱。我很想将所有这些文件放在一个“子文件夹”中

class presentation(models.Model):
    """ Holds the presentation themselves"""
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    file = models.FileField(
        null=False,
        blank=False,
        help_text='PPT or other presentation accessible only to members',
        storage=protected_storage,
    )

protected_storage = storages.backends.s3boto3.S3Boto3Storage(
    acl='private',
    querystring_auth=True,
    querystring_expire=120,  # 2 minutes, try to ensure people won't/can't share
)

1 个答案:

答案 0 :(得分:1)

添加upload_to参数并使其指向函数。

def my_upload_func(instance, filename):
    return f"test/awesome/{filename}"

file = models.FileField(
        null=False,
        blank=False,
        help_text='PPT or other presentation accessible only to members',
        storage=protected_storage,
        upload_to=my_upload_func
)
相关问题