Search code examples
pythonmysqlamazon-web-servicesaws-lambdapymysql

AWS Lambda function returning same values unless redeployed


I have a simple AWS Lambda function connected to a mysql rds. When I update a field in my apps UI it updates it in the database when viewed from the MySQL workbench but when using the Lambda function it returns the same value until I redeploy the function and then it gives me the new correct value

"""Search Function for Lambda""" 

from urllib.parse import unquote
import json
import pymysql

# Configuration Values
##CONFIG VALUES REMOVED


# Connection
connection = pymysql.connect(ENDPOINT, user=USERNAME,
                             passwd=PASSWORD, db=DATABASE_NAME)


def get(event, context):
    """Takes searches key from event and searches the database on that key"""
    print(context)
    cursor = connection.cursor()
    search_key = unquote(event['pathParameters']['search_key'])
    cmd = ('SELECT * from LCI_Data WHERE Description Like "{}"'.format("%"+search_key+"%"))
    cursor.execute(cmd)
    result = [dict((cursor.description[i][0], value)
              for i, value in enumerate(row)) for row in cursor.fetchall()]

    response = {
                "statusCode": 200,
                "body": json.dumps(result),
                "headers": {
                    "Access-Control-Allow-Origin": "*",
                    "Access-Control-Allow-Credentials": "true"
                }
            }
    return response


Solution

  • Moving

    connection = pymysql.connect(ENDPOINT, user=USERNAME,
                                 passwd=PASSWORD, db=DATABASE_NAME) 
    

    into the get() function solved my issues.