admin管理员组

文章数量:1022679

I have check my file a lot of time and I think I have already create the lambda_handler in my lambda_function.py. It still did not work.

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"/{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))

    #     connmit()
    #     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.')
        }

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

I have upload a file in this structure

lambda_function.py
boto3/
psycopg2/
requests/

but in the aws

lambda_function/lambda_function.py
boto3/
psycopg2/
requests/

so I move the lambda_function.py out to try and test the function it gives me an error Response: { "errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'", "errorType": "Runtime.HandlerNotFound", "requestId": "", "stackTrace": [] }

I have check my file a lot of time and I think I have already create the lambda_handler in my lambda_function.py. It still did not work.

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/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))

    #     connmit()
    #     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.')
        }

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

I have upload a file in this structure

lambda_function.py
boto3/
psycopg2/
requests/

but in the aws

lambda_function/lambda_function.py
boto3/
psycopg2/
requests/

so I move the lambda_function.py out to try and test the function it gives me an error Response: { "errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'", "errorType": "Runtime.HandlerNotFound", "requestId": "", "stackTrace": [] }

Share Improve this question asked Nov 19, 2024 at 8:32 fangle xifangle xi 31 bronze badge 1
  • Are you uploading your code manually via the GUI or using something like SAM or CloudFormation ? – AN63L Commented Nov 19, 2024 at 16:01
Add a comment  | 

1 Answer 1

Reset to default 0

Try to zip your files using CLI directly using:

zip -r deployment_package.zip lambda_function.py boto3/ psycopg2/ requests/

this will make sure that you have your lambda_function.py in the root directory.

for the lambda_handler, try to define from the lambda aws console:

def lambda_handler(event, context):
    pass 

and see if you will keep getting the same error. you already got another structure for your files, so you may have uploaded a wrong zip file.

I have check my file a lot of time and I think I have already create the lambda_handler in my lambda_function.py. It still did not work.

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"/{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))

    #     connmit()
    #     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.')
        }

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

I have upload a file in this structure

lambda_function.py
boto3/
psycopg2/
requests/

but in the aws

lambda_function/lambda_function.py
boto3/
psycopg2/
requests/

so I move the lambda_function.py out to try and test the function it gives me an error Response: { "errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'", "errorType": "Runtime.HandlerNotFound", "requestId": "", "stackTrace": [] }

I have check my file a lot of time and I think I have already create the lambda_handler in my lambda_function.py. It still did not work.

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/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))

    #     connmit()
    #     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.')
        }

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

I have upload a file in this structure

lambda_function.py
boto3/
psycopg2/
requests/

but in the aws

lambda_function/lambda_function.py
boto3/
psycopg2/
requests/

so I move the lambda_function.py out to try and test the function it gives me an error Response: { "errorMessage": "Handler 'lambda_handler' missing on module 'lambda_function'", "errorType": "Runtime.HandlerNotFound", "requestId": "", "stackTrace": [] }

Share Improve this question asked Nov 19, 2024 at 8:32 fangle xifangle xi 31 bronze badge 1
  • Are you uploading your code manually via the GUI or using something like SAM or CloudFormation ? – AN63L Commented Nov 19, 2024 at 16:01
Add a comment  | 

1 Answer 1

Reset to default 0

Try to zip your files using CLI directly using:

zip -r deployment_package.zip lambda_function.py boto3/ psycopg2/ requests/

this will make sure that you have your lambda_function.py in the root directory.

for the lambda_handler, try to define from the lambda aws console:

def lambda_handler(event, context):
    pass 

and see if you will keep getting the same error. you already got another structure for your files, so you may have uploaded a wrong zip file.

本文标签: