How to have more than one handler in AWS Lambda Function?

≡放荡痞女 提交于 2019-12-25 02:16:46

问题


I have a very large python file that consists of multiple defined functions. If you're familiar with AWS Lambda, when you create a lambda function, you specify a handler, which is a function in the code that AWS Lambda can invoke when service executes my code, which is represented below in my_handler.py file:

    def handler_name(event, context):
    ...
    return some_value

Link Source: https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html

However, as I mentioned above, I have multiple defined functions in my_handler.py that have their own events and contexts. Therefore, this will result in an error. Are there any ways around this in python3.6?


回答1:


Your single handler function will need to be responsible for parsing the incoming event, and determining the appropriate route to take. For example, let's say your other functions are called helper1 and helper2. Your Lambda handler function will inspect the incoming event and then, based on one of the fields in the incoming event (ie. let's call it EventType), call either helper1 or helper2, passing in both the event and context objects.

def handler_name(event, context):
  if event['EventType'] = 'helper1':
    helper1(event, context)
  elif event['EventType'] = 'helper2':
    helper2(event, context)

def helper1(event, context):
  pass

def helper2(event, context):
  pass

This is only pseudo-code, and I haven't tested it myself, but it should get the concept across.



来源:https://stackoverflow.com/questions/50687152/how-to-have-more-than-one-handler-in-aws-lambda-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!