2016-01-15 155 views
2

boto3文檔建議通過命令行配置密鑰。如果無論如何,我可以把AWS密鑰放入Python源代碼中?以下是供參考的代碼。boto3 S3使用aws密鑰上傳

If you have the AWS CLI, then you can use its interactive configure command to set up your credentials and default region: 
aws configure 
Follow the prompts and it will generate configuration files in the correct locations for you. 

import boto3 

s3 = boto3.resource('s3') 
bucket = s3.Bucket('my-bucket') 
for obj in bucket.objects.all(): 
    print(obj.key) 
+0

不推薦。如果密鑰被撤銷並且新的密鑰被分配並且對憑證文件做出改變。由於舊密鑰,連接將失敗。 也許你可以添加多個配置文件並調用特定的配置文件。 https://github.com/boto/boto3/issues/21 – mootmoot

回答

9

參見'方法參數'in the official documentation;

from boto3.session import Session 

session = Session(aws_access_key_id='<YOUR ACCESS KEY ID>', 
        aws_secret_access_key='<YOUR SECRET KEY>', 
        region_name='<REGION NAME>') 
_s3 = session.resource("s3") 
_bucket = _s3.Bucket(<BUCKET NAME>) 
_bucket.download_file(Key=<KEY>, Filename=<FILENAME>) 
+0

所以我做my_s3 = session.resource('s3')得到我的S3對象? – user1187968

+0

這就是頁面所說的。 – bmargulies