2016-01-15 161 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