santosh
santosh

Reputation: 4149

Class based AWS lambda in Python

I have created a class based AWS lambda function in python called requestHandler.py as below

from action_dispatcher import ActionDispatcher

class RequestHandler(ActionDispatcher):


    @staticmethod
    def createTemplate(event, context):
        return "Hello world"

My action_dispatcher.py is as shown below.

import json

class ActionDispatcher(object):

    def __call__(self, event, context, *args, **kwargs):

        action = event.get('action')
        handler = getattr(self, action, None)

        if handler is None:
            return json.loads({'status': 'error', 'code': 404, 'message':"Action {0} not found.".format(action) })

        return handler(request, *args, **kwargs)

With this above setup and lambda handler as requestHandler.RequestHandler, i get error "RequestHandler() takes no arguments" in this case i create action as createTemplate. so i want to call this method from RequestHandler.

Upvotes: 4

Views: 11304

Answers (3)

santosh
santosh

Reputation: 4149

The solution for my problem was simple, as mentioned by jacinator, i should try with class instance. earlier for lambda handler, i used pass class as handler, now i am passing the instance of the class as handler. Added the line in requestHandler.py rhandler = RequestHandler() So previously my lambda handler was like requestHandler.RequestHandler, now it has been changed to requestHandler.rhandler.

Upvotes: 0

Deiv
Deiv

Reputation: 3097

You can only define a handler in python using def handler(event, context):. However, I found a package that allows you to call the handler as a class

Usage, as noted in their documentation, is as follows:

pip install aws-lambda-handler

import aws_lambda

class EchoHandler(aws_lambda.Handler):
    """Echo handler."""

    def perform(self, request, **k):
        """Echo perform method."""
        response = aws_lambda.Response()
        response.body = self.request.event
        return response

echo_handler = EchoHandler()

# `echo_handler` is now a callable function you can map your AWS Lambda function to

Upvotes: 1

Jacinator
Jacinator

Reputation: 1413

It looks to me like you are trying to call your class instead of an instance of the class. RequestHandler() will call the __init__ method to initialize an instance of the class. Since you haven't defined the method it doesn't take any arguments. To access __call__ you need to call an instance of your class.

handler = RequestHandler()
result = handler(request, context, *args, **kwargs)

Upvotes: 2

Related Questions