Last active
June 9, 2022 01:36
-
-
Save byrro/439d233636ac6894f87c1df6ff1fa298 to your computer and use it in GitHub Desktop.
Asynchronous HTTP requests to AWS Lambda API endpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Non-blocking concurrent requests to AWS Lambda API endpoints | |
with Python asyncio and aiohttp | |
HOW TO: | |
1. Prepare a list of invocation parameters: | |
requests = [ | |
{ | |
'function_name': 'your-lambda-function', | |
'payload': { | |
'hello': 'world', | |
}, | |
}, | |
{ | |
'function_name': 'yet-another-function', | |
'payload': { | |
'foo': 'bar', | |
}, | |
] | |
2. Call the invoke_all method: | |
results = invoke_all( | |
requests=requests, | |
region='us-east-1', # Any valid AWS region | |
) | |
3. Results will be returned in the same order of requests | |
Credits to Mathew Marcus (2019) | |
https://www.mathewmarcus.com/blog/ | |
http://archive.is/nXkCb | |
''' | |
import asyncio | |
import json | |
import os | |
from typing import Dict, List | |
import urllib | |
import aiohttp | |
from botocore import session, awsrequest, auth | |
LAMBDA_ENDPOINT = 'https://lambda.{region}.amazonaws.com/2015-03-31/functions' | |
AWS_CREDENTIALS = session.Session().get_credentials() | |
def sign_headers(*, url: str, payload: Dict): | |
'''Sign AWS API request headers''' | |
segments = urllib.parse.urlparse(url).netloc.split('.') | |
service = segments[0] | |
region = segments[1] | |
request = awsrequest.AWSRequest( | |
method='POST', | |
url=url, | |
data=json.dumps(payload), | |
) | |
auth.SigV4Auth(AWS_CREDENTIALS, service, region).add_auth(request) | |
return dict(request.headers.items()) | |
async def invoke(*, url: str, payload: Dict, session): | |
'''Invoke a Lambda function''' | |
signed_headers = sign_headers(url=url, payload=payload) | |
async with session.post(url, json=payload, headers=signed_headers) \ | |
as response: | |
return await response.json() | |
def run_invocations( | |
*, | |
requests: List, | |
base_url: str, | |
session, | |
async: bool, | |
): | |
for request in requests: | |
method = 'invoke-async' if async is True else 'invocations' | |
url = os.path.join(base_url, request['function_name'], method) | |
yield invoke(url=url, payload=request['payload'], session=session) | |
def invoke_all( | |
*, | |
requests: List, | |
region: str = 'us-east-1', | |
async: bool = False, | |
): | |
base_url = LAMBDA_ENDPOINT.format(region=region) | |
async def wrapper(): | |
async with aiohttp.ClientSession(raise_for_status=True) as session: | |
invocations = run_invocations( | |
requests=requests, | |
base_url=base_url, | |
session=session, | |
async=async, | |
) | |
return await asyncio.gather(*invocations) | |
loop = asyncio.get_event_loop() | |
results = loop.run_until_complete(wrapper()) | |
return results |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The code in this gist (async_lambda.py) is licensed under the following terms: | |
MIT License | |
Copyright (c) 2019 Renato Byrro | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
boto3>=1.9.183 | |
aiohttp>=3.5.4 |
Hi i am new in python so can you explain me how i install the xlibs ? pip shows me an xlib library but not an xlibs.
from xlibs import constants
thanks in advance
Hi @Zafer83, I cleaned it up. I actually had this script in another project and forgot to remove this import when I extracted as a gist. Sorry about that, it's fixed now. Thanks for pointing it out!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi i am new in python so can you explain me how i install the xlibs ? pip shows me an xlib library but not an xlibs.
from xlibs import constants
thanks in advance