【问题标题】:Aws Lambda "Runtime.HandlerNotFound" pythonAws Lambda“Runtime.HandlerNotFound”python
【发布时间】:2021-10-11 04:56:51
【问题描述】:

我是 python 和 AWS lambda 的新手。我正在尝试从 lambda 函数运行此脚本,但出现错误:

Runtime.HandlerNotFound

如果我从 ec2 实例运行此脚本,它可以正常工作,但是当我从 AWS lambda 运行相同的脚本时,它会引发错误。

如果有人指导我做错了什么,我将非常感激。

谢谢


    import boto3
    import requests
    import time
    
    AWS_Access_Key_ID = 
    AWS_Secret_Access_Key = 
    
    DELAY_TIME=10 # 10 Seconds
    
    region = 'us-east-2'
    # instances = ['']
    
    instances = {
      'instance id': 'http://link',
      'instance id': 'http://link'
      
    }
    
    ec2 = None
    
    try:
      ec2 = boto3.client('ec2', aws_access_key_id=AWS_Access_Key_ID, aws_secret_access_key=AWS_Secret_Access_Key, region_name=region)
      # ec2 = boto3.resource('ec2',aws_access_key_id=AWS_Access_Key_ID, aws_secret_access_key=AWS_Secret_Access_Key, region_name=region)
    except Exception as e:
      print(e)
      print("AWS CREDS ERROR, Exiting...")
      exit()
    
    def startInstances(instancesIds):
      if(type(instancesIds) != list):  
        instancesIds = [instancesIds]
    
      try:
        response = ec2.start_instances(InstanceIds=instancesIds, DryRun=False)
        print(response)
        print("Instances Started")
      except ClientError as e:
        print(e)
        print("Instances Failed to Start")
    
    def stopInstances(instancesIds):
      if(type(instancesIds) != list):  
        instancesIds = [instancesIds
        ]
      try:
        response = ec2.stop_instances(InstanceIds=instancesIds, DryRun=False)
        print(response)
        print("Instances Stopped")
      except ClientError as e:
        print(e)
        print("Instances Failed to Stop")
    
    def check():
      for x in instances:
        retry = 0
        live = False
    
        print("Checking Webiste " + instances[x])
    
        while(retry < 5):
          try:
            r = requests.get(instances[x] ,verify=True)
            if(r.status_code == 200):
              live = True
            break
          except: 
            print("Not Live, retry time " + str(retry + 1))
            print("Delaying request for " + str(DELAY_TIME) + " seconds...")
            retry += 1
            time.sleep(DELAY_TIME)
    
        if(live):
          print("Website is live")
          # call function  to start the ec2 instance
          startInstances(x)
        else:
          # call function to stop the ec2 instance
          print('Website is dead') 
          stopInstances(x)   
        print("")
    
    def main():
      check()
    
    if __name__ == '__main__':
      main()

【问题讨论】:

  • 你能分享一下你的lambda的配置吗?没有它,就不可能知道为什么会出现此错误。
  • 您的函数没有任何处理程序。您是否查看了有关如何在 python 中创建 lambda 函数的 aws 文档?顺便说一句,像这样硬编码凭证是一个非常糟糕的主意。
  • 尝试在控制台中设置处理程序,下一个模式 file_name.function_name 在您的情况下可能是 file_name.main
  • 将 sleep 引入 lambda 函数是个坏主意。最好每秒运行一次函数,而不是让函数休眠一秒钟。
  • @ChristianDanielAvilaSanchez 感谢您的回复,现在我收到此错误,{“errorMessage”:“main() 接受 0 个位置参数,但给出了 2 个”,“errorType”:“TypeError”, "stackTrace": [" File \"/var/runtime/bootstrap.py\", line 127, in handle_event_request\n response = request_handler(event, lambda_context)\n" ] }

标签: python-3.x amazon-web-services amazon-ec2 aws-lambda


【解决方案1】:

https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html 您需要指定处理函数的名称是什么,这是 AWS lambda 将调用的函数。然后你需要在你的 Python 脚本中实现这个函数。

【讨论】:

    【解决方案2】:

    我最近遇到了类似的问题。我能够在解决问题的 python 代码中定义一个 lambda 处理函数。得到this post的指导

    简而言之,添加此代码(相应地调整命名约定):

    import botocore
    import boto3
    
    def lambda_handler(event, context):
        s3 = boto3.resource('s3')
        bucket = s3.Bucket('bucketname')
        exists = True
    
        try:
            s3.meta.client.head_bucket(Bucket='bucketname')
        except botocore.exceptions.ClientError as e:
            # If a client error is thrown, then check that it was a 404 error.
            # If it was a 404 error, then the bucket does not exist.
            error_code = int(e.response['Error']['Code'])
            if error_code == 404:
                exists = False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-21
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-14
      • 2019-10-07
      • 2016-10-10
      • 2022-11-28
      相关资源
      最近更新 更多