2016-05-04 96 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。不要忘記 - 它適合我!

我希望有所幫助。

相關問題