5

I have a zappa lambda deployed at arn:aws:lambda:us-east-1:xxxxx:function:xx-xx-prod, which serves a route like so:

@app.route('/test', methods=['POST'])
def test():
    response = app.response_class(
      response=get_jsonstr({'test': 'OK'}),
      status=200,
      mimetype='application/json'
    )
    return response

I want to invoke the above test() function from another lambda function like so:

client = boto3.client('lambda', region_name='us-east-1')
r = client.invoke(
  FunctionName='arn:aws:lambda:us-east-1:xxxxx:function:xx-xx-prod',
  InvocationType='RequestResponse',
  LogType='None',
  Payload='',
)
print(r)
print(json.loads(r['Payload'].read()))

The above call succeeds like so:

{
  'ResponseMetadata': {
    'RequestId': '37ecc17b-03a9-11e9-9ea0-9dee231dfb79',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'date': 'Wed, 19 Dec 2018 16:14:55 GMT',
      'content-type': 'application/json',
      'content-length': '4',
      'connection': 'keep-alive',
      'x-amzn-requestid': '37ecc17b-03a9-11e9-9ea0-9dee231dfb79',
      'x-amzn-remapped-content-length': '0',
      'x-amz-executed-version': '$LATEST',
      'x-amzn-trace-id': 'root=1-5c1a6e7d-8063e5004eab150d6c967b0;sampled=0'
    },
    'RetryAttempts': 0
  },
  'StatusCode': 200,
  'ExecutedVersion': '$LATEST',
  'Payload': <botocore.response.StreamingBody object at 0x11296ce10>
}
None

How do I tell the zappa handler to invoke the test() function?

Update:

I found that I can add a custom handler in zappa_settings.json like so:

"lambda_handler": "lambdafilename.test"

Then, I changed the test() like so:

@app.route('/test', methods=['POST'])
def test(event=None, context=None):
  return json.dumps({'test': 'OK1'})

Now, the invocation returns the expected result:

{"test": "OK1"}

However, with this custom handler, I lose the WSGI functionality that zappa/flask provides.

gilch
  • 8,571
  • 1
  • 16
  • 26
kriss
  • 51
  • 5

1 Answers1

0

I had a look into the source code of the Zappa CLI to figure out how the zappa invoke command works internally because that's exactly what we want: Remotely and programmatically invoke a specific function within your Zappa lambda.

payload = {'command': '<module_path>.lambda_handler_function'}
client = boto3.client('lambda', region_name='us-east-1')
client.invoke(
  FunctionName='arn:aws:lambda:<arn>:function:<your_zappa_lambda_name>',
  InvocationType='RequestResponse',
  LogType='Tail',
  Payload=json.dumps(payload),
)

Keep in mind that your function has to accept the lambda event and context to be a valid entry point.

For more information on how the zappa invoke command works:

if command == 'invoke'

command = {key: function_name}

Stephan Schielke
  • 2,456
  • 7
  • 29
  • 39