如何使用boto3和serializer将私有文件上传到s3

时间:2018-01-22 23:30:53

标签: django file amazon-s3 boto3 serializer

我正在使用S3Boto3Storage管理私人文件上传到s3。当我通过模型上传时,上传按预期工作。

当我通过序列化程序上传时,出现此错误:

 botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found

以下是我的文件:

// storage_backend.py

class PrivateFileStorage(S3Boto3Storage):
    location = settings.AWS_PRIVATE_FILE_LOCATION
    default_acl = 'private'
    file_overwrite = False
    custom_domain = False

// settings.py

 DEFAULT_FILE_STORAGE = 'myapp.storage_backend.PrivateFileStorage'

// models.py

class PrivateFileModel(models.Model):
    file = models.FileField(storage=PrivateFileStorage())

// serializers.py

class PrivateFileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = PrivateFileModel
        fields = ('url', 'file')

// views.py

 json_obj = json.dumps(<some_object>)
 file_name = "{}".format(str(uuid.uuid1()))
 file = default_storage.open(file_name, 'w')
 file.write(json_obj)

 serializer = self.get_serializer(data={'file':file})
 serializer.is_valid(raise_exception=True) # throws error

 # # saving the file directly to the model works just fine
 # file_instance = PrivateFileModel(file=file)
 # file_instance.save() 

如何将boto3存储与django rest serializer集成?

0 个答案:

没有答案