尝试导入lambda时,没有名为“ requests_aws4auth”的模块

时间:2018-08-15 12:49:07

标签: python python-3.x amazon-web-services aws-lambda python-3.6

我需要我的lambda来调用API网关,并在我的云形成模板中放置以下代码作为lambda的内联代码。

from requests_aws4auth import AWS4Auth
def handler(event,context):
          client = boto3.client('sts')
          responseAssumeRole = client.assume_role(
            DurationSeconds=3600,
            RoleArn='arn',// real arn of the api gateway invocation role
            RoleSessionName='Bob',
          )
          credentials = responseAssumeRole['Credentials']
          auth = AWS4Auth(aws_access_key=responseAssumeRole['Credentials']['AccessKeyId'],
                                 aws_secret_access_key=responseAssumeRole['Credentials']['SecretAccessKey'],
                                 aws_host='host.execute-api.us-east-1.amazonaws.com',
                                 aws_region='us-east-1',
                                 aws_service='execute-api')
          headers= {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}
          response = requests.get('https://host.execute-api.us-east-1.amazonaws.com/test',
                                  auth=auth, headers=headers)

这给了我以下错误

No module named 'requests_aws4auth'

也欢迎任何使用aws凭证创建身份验证的解决方案或替代方法。

2 个答案:

答案 0 :(得分:3)

将您的源代码和依赖项打包为一个zip文件,将其上传到S3,然后在您的AWS :: Lambda :: Function资源下使用S3Bucket和S3Keys属性。

例如在Linux上:

mkdir project-dir
cp myhandler.py project-dir
pip install module-name -t /path/to/project-dir

# zip the contents of project-dir , this is your deployment package
cd project-dir
zip -r deployme.zip .

答案 1 :(得分:0)

尽管接受的答案有效,但我也想发布此资源。如果您不想打包并将其上传到S3并仍在寻找替代方法以在嵌入式Lambda中具有相同功能,则将有所帮助。如果您使用这种方法,则无需首先使用“ requests_aws4auth”。

https://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html

您可以替换以下

access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')

带有您从承担角色请求中获得的值,像这样

access_key=responseAssumeRole['Credentials']['AccessKeyId']
secret_key=responseAssumeRole['Credentials']['SecretAccessKey']