gpt4 book ai didi

python-3.x - 如何使用 python asyncio 从 EC2 实例调用 AWS Lambda 函数

转载 作者:行者123 更新时间:2023-12-02 00:58:17 24 4
gpt4 key购买 nike

我最近发布了一个关于 How to allow invoking an AWS Lambda function only from EC2 instances inside a VPC 的问题。我设法通过将具有“AWS lambda 角色”策略的 IAM 角色附加到 EC2 实例来使其正常工作,现在我可以使用 boto3 调用 lambda 函数。

现在,我想使用 asyncio wait 语法异步调用 lambda 函数。我读到 lambda 函数通过设置 InvokeType='Event' 提供异步版本。 ,但这实际上使调用立即返回,而没有获得函数的结果。

由于该函数需要一些时间,并且我想并行启动许多函数,因此我希望避免在等待函数返回时阻塞执行。

我尝试使用 aiobotocore,但这仅支持基本的“s3”服务功能。

解决此问题的最佳方法(以拙见)是使用 AWS API Gateway 服务通过 GET/POST 请求调用 lambda 函数,该请求可以使用 aiohttp 轻松处理。

尽管如此,我还是没能让它发挥作用。

我向 EC2 IAM 角色添加了策略“AmazonAPIGatewayInvokeFullAccess”,但每次我尝试:

import requests
r = requests.get('https://url_to_api_gateway_for_function')

我收到禁止回复 <Response [403]> .

我直接使用 lambda 函数中的触发器创建了 API 网关。

我还尝试编辑 API 网关设置,方法是向函数路径添加 post 方法并设置“AWS_IAM”身份验证,然后将其部署为“prod”部署...没有运气。还是同样的禁止 react 。当我通过“API网关上的测试屏幕测试它时,它工作正常”。

知道如何解决这个问题吗?我错过了一些步骤吗?

最佳答案

经过一番努力,我终于解决了我的问题。

问题在于,curl 和 python 模块(例如 python 的 requests)不会使用运行它们的 EC2 计算机的 IAM 凭证对 http 请求进行签名。对 AWS GATEWAY API 的 http 请求必须使用 AWS v4 登录协议(protocol)进行签名。

示例如下: http://docs.aws.amazon.com/general/latest/gr/sigv4-signed-request-examples.html

幸运的是,为了简单起见,有一些帮助器模块,例如 requests-aws-sign: https://github.com/jmenga/requests-aws-sign

最后代码可能看起来像这样:

import aiohttp
import asyncio
from requests_aws_sign import AWSV4Sign
from boto3 import session

session = session.Session()
credentials = session.get_credentials()
region = session.region_name or 'ap-southeast-2'
service = 'execute-api'
url = "get_it_from_api->stages->your_deployment->invoke_url"
auth=AWSV4Sign(credentials, region, service)

async def invoke_func(loop):
async with aiohttp.request('GET', url, auth=auth, loop=loop) as resp:
html = await resp.text()
print(html)

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))

希望这能为其他人节省时间!

编辑:

为了完整性和帮助其他人,我不得不说上面的代码不起作用,因为 requests_aws_sign 与 aiohttp 不兼容。我收到一些“验证字段错误”。

我设法用以下方法解决了这个问题:

async with session.get(url, headers=update_headers()) as resp:

其中 update_headers() 是一个简单的函数,它模仿 requests_aws_sign 对 header 所做的操作(以便我可以使用 header 参数将它们直接设置为上面的请求)。它看起来像这样:

def update_headers(sim_id):
url = urlparse("get_it_from_api->stages->your_deployment->invoke_url")
path = url.path or '/'
querystring = ''
if url.query:
querystring = '?' + urlencode(parse_qs(url.query), doseq=True)
safe_url = url.scheme + '://' + url.netloc.split(':')[0] + path + querystring
request = AWSRequest(method='GET', url=safe_url)
SigV4Auth(credentials, service, region).add_auth(request)
return dict(request.headers.items())

关于python-3.x - 如何使用 python asyncio 从 EC2 实例调用 AWS Lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43292567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com