17

我在 aws lambda 中使用 boto3 来感染位于法兰克福地区的 S3 中的对象。

v4 是必要的。否则将返回以下错误

"errorMessage": "An error occurred (InvalidRequest) when calling 
the GetObject operation: The authorization mechanism you have 
provided is not supported. Please use AWS4-HMAC-SHA256."

配置signature_version的实现方法http://boto3.readthedocs.org/en/latest/guide/configuration.html

但由于我使用的是 AWS lambda,因此我无权访问底层配置文件

我的 AWS lambda 函数的代码

from __future__ import print_function
import boto3


def lambda_handler (event, context):
    input_file_bucket = event["Records"][0]["s3"]["bucket"]["name"]
    input_file_key = event["Records"][0]["s3"]["object"]["key"]
    input_file_name = input_file_bucket+"/"+input_file_key

    s3=boto3.resource("s3")
    obj = s3.Object(bucket_name=input_file_bucket, key=input_file_key)
    response = obj.get()
    return event #echo first key valuesdf

是否可以在此代码中配置 signature_version ?以会话为例。或者有什么解决方法吗?

4

2 回答 2

25

尝试使用自定义会话和来自 boto3.session 的配置,而不是使用默认会话

import boto3
import boto3.session
session = boto3.session.Session(region_name='eu-central-1')
s3client = session.client('s3', config= boto3.session.Config(signature_version='s3v4'))
s3client.get_object(Bucket='<Bkt-Name>', Key='S3-Object-Key')
于 2015-11-12T10:03:15.940 回答
6

我尝试了会话方法,但遇到了问题。这种方法对我来说效果更好,您的里程可能会有所不同:

s3 = boto3.resource('s3', config=Config(signature_version='s3v4'))

您需要从 botocore.client 导入 Config 才能完成这项工作。有关测试存储桶(列出对象)的功能方法,请参见下文。这假设您是在管理身份验证的环境中运行它,例如 Amazon EC2 或具有 IAM 角色的 Lambda:

import boto3
from botocore.client import Config
from botocore.exceptions import ClientError

def test_bucket(bucket):
    print 'testing bucket: ' + bucket
    try:
        s3 = boto3.resource('s3', config=Config(signature_version='s3v4'))
        b = s3.Bucket(bucket)
        objects = b.objects.all()

        for obj in objects:
            print obj.key
        print 'bucket test SUCCESS'
    except ClientError as e:
        print 'Client Error'
        print e
        print 'bucket test FAIL'

要对其进行测试,只需使用存储桶名称调用该方法。您的角色必须授予适当的权限。

于 2016-11-02T17:50:19.923 回答