Search code examples
pythonamazon-web-servicesaws-lambdapymysql

"errorMessage": "lambda_handler() takes 0 positional arguments but 2 were given",


This code works correctly in my machine but getting error in AWS Lambda:

import pymysql

dbhost = 'database.ap-south-1.rds.amazonaws.com'
dbuser = 'admin'
dbpass = 'admin123'
dbname = 'classicmodels'
connection = pymysql.connect(host=dbhost, user=dbuser, password=dbpass, database=dbname)

def lambda_handler():
  cursor = connection.cursor()
  cursor.execute('SELECT * FROM Persons')
  rows = cursor.fetchall()
  for row in rows:
    print ("{0} {1} {2}".format(row[0], row[1], row[2]))

lambda_handler()
{
"errorMessage": "lambda_handler() takes 0 positional arguments but 2 were given",
"errorType": "TypeError",
"requestId": "fb790715-91f1-4f7a-961f-b83485d23b68",
"stackTrace": ["  File \"/var/runtime/awslambdaric/bootstrap.py\", line 149, in handle_event_request\n    response = request_handler(event, lambda_context)\n"
]
}

Function Logs
START RequestId: fb790715-91f1-4f7a-961f-b83485d23b68 Version: $LATEST
[ERROR] TypeError: lambda_handler() takes 0 positional arguments but 2 were given
Traceback (most recent call last):
File "/var/runtime/awslambdaric/bootstrap.py", line 149, in handle_event_request
response = request_handler(event, lambda_context)END RequestId: fb790715-91f1-4f7a-961f-b83485d23b68
REPORT RequestId: fb790715-91f1-4f7a-961f-b83485d23b68  Duration: 1.07 ms   Billed Duration: 2 ms   Memory Size: 128 MB Max Memory Used: 44 MB

Solution

  • Do not call the handler:

    lambda_handler()
    

    The AWS Lambda service will call the handler when the function is invoked.

    Also, the Lambda function should be defined as:

    def lambda_handler(event, context):
    

    The event will contain information about what triggered the event and the context will contain information about the Lambda deployment environment.