You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda报错lambda_handler缺失,已定义函数仍无法解决求助

Lambda HandlerNotFound 问题排查与解决

核心问题

确认lambda_function.py中存在lambda_handler函数,但AWS Lambda返回Handler 'lambda_handler' missing on module 'lambda_function'错误,调整文件结构后问题依旧。

排查与修复步骤

1. 严格检查部署包结构

你反馈初始上传结构为:

lambda_function.py
boto3/
psycopg2/
requests/

但AWS中显示为嵌套结构:

lambda_function/lambda_function.py
boto3/
psycopg2/
requests/

即使移出文件后仍报错,需确保:

  • 重新打包时,lambda_function.py必须直接位于压缩包根目录,不能嵌套任何子文件夹。
  • 打包操作需进入目标文件夹,选中所有文件/文件夹后压缩,避免将父目录打包进去。

2. 验证Lambda处理程序配置

登录AWS Lambda控制台,检查函数配置:

  • 确认“处理程序”字段设置为lambda_function.lambda_handler(格式为[文件名].[函数名],此处文件名是lambda_function.py,对应模块名lambda_function,函数名lambda_handler)。
  • 若曾修改文件名或函数名,需同步更新该配置。

3. 清理冗余/不兼容依赖

注意Lambda运行时的自带依赖:

  • AWS Lambda已预装boto3,无需手动打包,多余的boto3包可能引发模块加载冲突。
  • psycopg2需针对Lambda运行环境(如Amazon Linux 2)编译,本地打包的版本大概率不兼容,建议使用psycopg2-binary或通过Lambda层部署依赖。
  • 仅保留Lambda未自带的依赖(如requests),减少打包体积与冲突概率。

4. 排查代码加载异常

虽然你确认lambda_handler存在,但需验证:

  • 本地Python环境中导入lambda_function模块,检查lambda_handler是否可正常访问(排除语法错误或模块加载失败)。
  • 代码中若有隐藏语法错误,会导致Lambda无法加载模块,进而返回Handler未找到的错误。

验证流程

  1. 新建临时文件夹,将lambda_function.py复制进去。
  2. 仅添加Lambda未自带的兼容依赖(如requests、适配Lambda的psycopg2)。
  3. 选中文件夹内所有内容,压缩为ZIP文件(不要压缩文件夹本身)。
  4. 重新上传ZIP包到Lambda,确认处理程序配置正确后测试。

附:你的代码

import json
import boto3
import psycopg2
from datetime import datetime, timedelta
import uuid
import os
# from dotenv import load_dotenv
import requests

# load_dotenv()
# Initialize AWS resources
sns = boto3.client('sns')


# db_url = os.environ['DB_URL']  # jdbc:postgresql://db_endpoint/db_name
# db_username = os.environ['DB_USERNAME']
# db_password = os.environ['DB_PASSWORD']


# db_host = db_url.split("://")[1].split("/")[0]  
# db_name = db_url.split("/")[-1]  


def send_verification_email(email, token):
    # Generate the verification link
    verification_link = f"https://{os.environ['DOMAIN_NAME']}/v1/user/verify?token={token}"

    # Send the email via Mailgun
    api_url = f"https://api.mailgun.net/v3/{os.environ['DOMAIN_NAME']}/messages"
    api_key = os.environ['MAILGUN_API_KEY']
    
    # Prepare the email data
    email_data = {
        "from": f"noreply@{os.environ['DOMAIN_NAME']}",
        "to": [email],
        "subject": "Verify Your Email Address",
        "text": f"Please verify your email by clicking the link: {verification_link}",
        # Optionally, you can include HTML content like this:
        # "html": f"<html><body><p>Please verify your email by clicking the link: <a href='{verification_link}'>Click here</a></p></body></html>"
    }
    
    # Send the email
    try:
        response = requests.post(
            api_url,
            auth=("api", api_key),
            data=email_data
        )
        if response.status_code == 200:
            return True
        else:
            print(f"Failed to send email: {response.text}")
            return False
    except Exception as e:
        print(f"Error sending email: {e}")
        return False

# def store_email_tracking(email, token):
    # Establish a connection to PostgreSQL
    # try:
    #     conn = psycopg2.connect(
    #         host=db_host,
    #         dbname=db_name,
    #         user=db_username,
    #         password=db_password
    #     )
    #     cursor = conn.cursor()

    #     # Store the email and token with an expiry time (2 minutes)
    #     expiry_time = datetime.now() + timedelta(minutes=2)
    #     cursor.execute("INSERT INTO email_tracking (email, token, expiry_time) VALUES (%s, %s, %s)",
    #                    (email, token, expiry_time))

    #     conn.commit()
    #     cursor.close()
    #     conn.close()
    # except Exception as e:
    #     print(f"Error storing email tracking info: {e}")

def lambda_handler(event, context):
    # Extract the email address from the SNS message
    message = json.loads(event['Records'][0]['Sns']['Message'])
    email = message['email']

    # Generate a unique token for the user
    token = str(uuid.uuid4())

    # Send the verification email
    if send_verification_email(email, token):
        # Store email tracking information
        # store_email_tracking(email, token)
        return {
            'statusCode': 200,
            'body': json.dumps('Verification email sent successfully.')
        }
    else:
        return {
            'statusCode': 500,
            'body': json.dumps('Failed to send verification email.')
        }

错误响应

{
"errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'",
"errorType": "Runtime.HandlerNotFound",
"requestId": "",
"stackTrace": []
}

初始上传文件结构

lambda_function.py
boto3/
psycopg2/
requests/

AWS中显示的结构

lambda_function/lambda_function.py
boto3/
psycopg2/
requests/

内容的提问来源于stack exchange,提问作者fangle xi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 04:17:32