別のラムダ関数からラムダ関数を呼び出すことはできますが、デフォルトではハンドラーメソッドに送られます。その中で定義されている他のメソッドを呼び出すにはどうすればよいですか?
ラムダ関数master.pyがあるとします。これには、他のラムダ関数で使用できる共通のメソッドがあるため、すべての関数で何度も何度も記述する必要はありません。ここで、他のラムダ関数からmaster.pyのメソッド(たとえばgetTime()、authenticateUser()など)を呼び出したいと思います。
基本的に、他のラムダ関数で使用できる一般的なメソッドを持つラムダ関数を保持したいと思います。
どんな助けでも大歓迎です。
以下は、あるラムダ関数を別のラムダ関数から呼び出そうとしたコードです(この質問からコードを取得しました)が、handler()メソッドに送られます。
def handler(event,context):
params = event['list']
return {"params" : params + ["abc"]}
import boto3
import json
lambda_client = boto3.client('lambda')
a=[1,2,3]
x = {"list" : a}
invoke_response = lambda_client.invoke(FunctionName="functionA",
InvocationType='RequestResponse',
Payload=json.dumps(x))
print (invoke_response['Payload'].read())
{
"params": [1, 2, 3, "abc"]
}
invokeの呼び出し時に、イベントパラメーター内で目的のラムダ関数メソッドを実行するために必要なデータを渡すことができます。呼び出したいメソッドを使用して、ラムダ関数のlambda_handlerの先頭に次のコードを含める場合。
def lambda_handler(event, context):
"""
Intermediary method that is invoked by other lambda functions to run methods within this lambda
function and return the results.
Parameters
----------
event : dict
Dictionary specifying which method to run and the arguments to pass to it
{function: "nameOfTheMethodToExecute", arguments: {arg1: val1, ..., argn: valn}}
context : dict
Not used
Returns
-------
object : object
The return values from the executed function. If more than one object is returned then they
are contained within an array.
"""
if "function" in event:
return globals()[event["function"]](**event["arguments"])
else:
# your existing lambda_handler code...
次に、メソッドを呼び出し、次のメソッドを使用して他のラムダ関数から戻り値を取得しますinvoke
。
import json
# returns the full name for a lambda function from AWS based on a given unique part
getFullName = lambda lambdaMethodName: [method["FunctionName"] for method in lambda_client.list_functions()["Functions"] if lambdaMethodName in method["FunctionName"]][0]
# execute a method in a different lambda function and return the results
def invoke(lambda_function, method_name, params):
# wrap up the method name to run and its parameters
payload = json.dumps({"function": method_name, "arguments": params})
# invoke the function and record the response
response = lambda_client.invoke(FunctionName=getFullName(lambda_function), InvocationType='RequestResponse', Payload=payload)
# parse the return values from the response
return json.loads(response["Payload"].read())
[rtn_val_1, rtn_val_2] = invoke("fromLambdaA", "desiredFunction", {arg1: val1, arg2: val2})
他のラムダ関数を呼び出す関数にアタッチされたラムダポリシーには、「lambda:ListFunctions」と「lambda:InvokeFunction」の2つのポリシーが必要であることに注意してください。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加