2016-05-04 102 views
2

我正在尝试将文件上载到S3存储桶,但我无法访问存储桶的根级别,因此我需要将其上传到某个代替前缀。下面的代码:使用Boto3将文件上传到带有前缀的S3存储桶

import boto3 
s3 = boto3.resource('s3') 
open('/tmp/hello.txt', 'w+').write('Hello, world!') 
s3_client.upload_file('/tmp/hello.txt', bucket_name, prefix+'hello-remote.txt') 

给我一个错误:

An error occurred (AccessDenied) when calling the PutObject operation: Access Denied: ClientError Traceback (most recent call last): File "/var/task/tracker.py", line 1009, in testHandler s3_client.upload_file('/tmp/hello.txt', bucket_name, prefix+'hello-remote.txt') File "/var/runtime/boto3/s3/inject.py", line 71, in upload_file extra_args=ExtraArgs, callback=Callback) File "/var/runtime/boto3/s3/transfer.py", line 641, in upload_file self._put_object(filename, bucket, key, callback, extra_args) File "/var/runtime/boto3/s3/transfer.py", line 651, in _put_object **extra_args) File "/var/runtime/botocore/client.py", line 228, in _api_call return self._make_api_call(operation_name, kwargs) File "/var/runtime/botocore/client.py", line 492, in _make_api_call raise ClientError(parsed_response, operation_name) ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied

bucket_name格式为abcdprefix的格式为a/b/c/d/。我不确定是否错误是由于斜线错误,或者是否有某种方法可以在其他地方指定前缀,或者如果我没有写入权限(尽管我本应该这样做)。

这段代码的执行没有任何错误:

for object in output_bucket.objects.filter(Prefix=prefix): 
    print(object.key) 

虽然没有输出的桶是空的。

回答

5

原来我需要SSE:

transfer = S3Transfer(s3_client) 
transfer.upload_file('/tmp/hello.txt', bucket_name, prefix+'hello-remote.txt', extra_args={'ServerSideEncryption': "AES256"}) 
+2

什么是's3_client'?它没有在任何地方定义。前缀也不是。 – pookie

+0

@foxes - 谢谢!我完全忘记了AES加密技术,并且不知道为什么它不起作用! –

1

我假设你有这一切设置:

  1. AWS访问密钥ID与密钥设置(通常存储在~/.aws/credentials
  2. 您可以访问S3,你知道你的水桶名&前缀(子目录)

按照Boto3 S3 upload_file documentation,您应该上传您上传这样的:

upload_file(Filename, Bucket, Key, ExtraArgs=None, Callback=None, Config=None)

import boto3 
s3 = boto3.resource('s3') 
s3.meta.client.upload_file('/tmp/hello.txt', 'mybucket', 'hello.txt') 

的关键,这里需要注意的是s3.meta.client。不要忘记 - 它适合我!

我希望有所帮助。

相关问题