Python AWS Lambda

Lambda functions invoked synchronously or fire-and-forget from Python services.

Zato lets you invoke AWS Lambda functions directly from your Python services. You create an AWS connection in the Dashboard and get the Lambda client through conn.client('lambda') - the explicit form is needed here because lambda is a reserved word in Python and cannot be an attribute name.

Invoking a function

# -*- coding: utf-8 -*-

# stdlib
import json

# Zato
from zato.server.service import Service

class ProcessOrder(Service):

    input = 'order_id'

    def handle(self):

        # Get the connection by its Dashboard name
        conn = self.aws['My AWS']

        # The Lambda client - lambda is a reserved word in Python,
        # so the explicit client() form is used.
        aws_lambda = conn.client('lambda')

        # Invoke the function and wait for its result
        payload = json.dumps({'order_id': self.request.input.order_id})

        response = aws_lambda.invoke(
            FunctionName='process-order',
            Payload=payload.encode('utf8'),
        )

        # Read the function's response
        result = response['Payload'].read()
        self.response.payload = json.loads(result)

Asynchronous invocation

To fire and forget, pass InvocationType='Event' - Lambda queues the invocation and the call returns immediately, without the function's result.

# -*- coding: utf-8 -*-

# stdlib
import json

# Zato
from zato.server.service import Service

class TriggerReportGeneration(Service):

    input = 'report_id'

    def handle(self):

        conn = self.aws['My AWS']
        aws_lambda = conn.client('lambda')

        payload = json.dumps({'report_id': self.request.input.report_id})

        response = aws_lambda.invoke(
            FunctionName='generate-report',
            InvocationType='Event',
            Payload=payload.encode('utf8'),
        )

        # 202 means the invocation was queued
        self.response.payload = {'status_code': response['StatusCode']}

Listing functions

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class ListFunctions(Service):

    def handle(self):

        conn = self.aws['My AWS']
        aws_lambda = conn.client('lambda')

        response = aws_lambda.list_functions()

        names = []
        for function in response['Functions']:
            names.append(function['FunctionName'])

        self.response.payload = {'functions': names}

More resources

Learn more