AWS Lambda function returning same values unless redeployed - python

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

Moving
connection = pymysql.connect(ENDPOINT, user=USERNAME,
passwd=PASSWORD, db=DATABASE_NAME)
into the get() function solved my issues.

Related

MongoDB returns empty data when I try to find data with python

I try to retrieve data from MongoDB, When I write the query in mongo CLI, Mongo retrieves data to me but When I run the exact same query in my Flask application mongo doesn't return any value to me.
#app.route("/getaddress", methods=['POST'])
def getaddress():
wallet_address_from_html = request.form["walletAddress"]
print("Address is correct and it's: ", wallet_address_from_html)
#MongoDB Search
mydb = cluster["the-merge"]
collection_wallet = mydb["wallet"]
myquery = { "wallet": wallet_address_from_html}
search_result = collection_wallet.find(myquery)
buffer_of_wallet= []
for address in search_result:
buffer_of_wallet.append(address)
print("BUFFER OF WALLET : ", buffer_of_wallet)
#buffer of wallet returns empty.
time.sleep(20)
wallet_address_from_html variable is correct, I checked 100 times, also I run this query db.wallet.find({"wallet": "15E33abb8aFB5C09969ff4BB2545Cf7BF8"}) on the MongoCLI and returns the correct value.
{ _id: 1,
username: 'root',
wallet: '15E33abb8aFB5C09969ff4BB2545Cf7BF8',
role: 'root' }
The above value is the value that I try to retrieve from mongo, As I said, When I run the query in CLI it runs correct but in getaddress method it doesn't give me the value.

mysql table not updating table - python mysql-connector

I have the following code to update a url in a table
from mysql.connector import Error
import mysql.connector
def update_url(self, data):
target_url = data['target_url']
try:
cnx = mysql.connector.connect(
host=os.getenv('mysql_host'),
port=os.getenv('mysql_port'),
user=os.getenv('mysql_user'),
password=os.getenv('mysql_password'),
database=os.getenv('mysql_database')
)
# Create Cursor
cur = cnx.cursor(dictionary=True)
# update target_url
cur.execute('''UPDATE client_url_info
SET target_url=%s
WHERE id=%s''', (data['client_id'], target_url))
cnx.commit()
change_url = {
'status': True,
'msg': 'Target URL has been successfully updated'
}
return change_url
except mysql.connector.Error as err:
change_error_url = {
'status': 'MYSQL_ERROR',
'msg': "Failed in MySQL: {}".format(err)
}
return change_error_url
finally:
if (cnx.is_connected()):
cnx.close()
for some reason I can add data and delete data, but when I try to use update it does not work.
based on other questions, the issue could be cause by the missing of commit() which in my case is included in the code.
I don´t know if I´m not looking right, the code seems to be fine and actually returns the successful msg after execution.
Table info:
Is there any other configuration I´m missing?
thanks in advance

Import Query String from AWS API Gateway into Lambda Python Function

I am working on creating a Lambda Function which imports query string information into a database but I'm running into some trouble accessing the query string itself in my python code. I have setup the proper string variables within the API Gateway and also enabled Lambda Proxy integration from the Integration Request section.
Some articles and previous responses said I should be doing so by using:
event["queryStringParameters"]['querystring1']
I've setup a handler and I'm curious how to pass the request body into the function my_handler
Here's a snippet of the code:
import logging, traceback, os
#environment variables
ep = os.environ["EP"]
p = os.environ["PORT"]
du = os.environ["USER"]
pw = os.environ["PASSWORD"]
db = os.environ["DATABASE"]
#query string variables
def my_handler(event):
servername = event["queryStringParameters"]["servername"]
hostDesc = event["queryStringParameters"]["description"]
hostRegion = event["queryStringParameters"]["region"]
response = servername + hostDesc + hostRegion
return {
'status code' : 200,
'body' : json.dumps(response)
}
This was due to an error.
I was trying to pass a SQL query later in the script via a global string by attempting to use the handler results. What should be done is defining the query as a function and call it during the handler. Once the handler has the event variables from the body request, they can be passed into the function.
EX:
import logging, traceback, json
def query(hostServername, hostDesc, hostRegion):
return "SELECT * FROM TABLE_NAME WHERE host ='"+hostIP+"' AND '"+hostPort+"' AND '"+hostServername+"'"
#query string variables
def my_handler(event):
server = event["queryStringParameters"]["servername"]
host = event["queryStringParameters"]["description"]
region = event["queryStringParameters"]["region"]
try:
cnx = some_database_connect_function()
cursor=cnx.cursor()
try:
cursor.execute(query(server, host, region))
return{
'Status Code' : 200
}
except:
return log_err ("ERROR: Cannot execute cursor.\n{}".format(
traceback.format_exc()) )
except:
return log_err("ERROR: Cannot connect to database from handler.\n{}".format(
traceback.format_exc()))

Return json using pymysql and Mysql Aurora DB

I using pymysql for connection to AWS Mysql Aurora DB. I created lambda function, which should return the data as json for use in the js framework.
def lambda_handler(event, context):
responses = []
try:
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
...
with conn.cursor() as cur:
cur.execute('SELECT * FROM Plans')
conn.commit()
for row in cur:
resp = {
"id": row[0],
"name": row[1],
...
...
"type": row[14],
}
responses.append(resp)
return responses
This code return list of dict.
I try to use json module result = json.dumps(responses), but this code return str
How can I get json?
The json module won't return you a JSON object.
json.loads()
will return a Python object using this formatting table.
json.dumps()
will return you a JSON formatted str using this formatting table.
You will be able to create a .json file using following code :
with open ('path/to/myfile.json', 'w') as myfile:
json.dump(responses, my_file)

My Lambda python Function is returning null even after successful execution

Am a beginner to AWS services and python, i used below code in lambda to connect
RDS and invoke this in API gateway
After Successful execution of below code it is returning null.
#!/usr/bin/python
import sys
import logging
import pymysql
import json
rds_host="host"
name="name"
password="password"
db_name="DB"
port = 3306
def save_events(event):
"""
This function fetches content from mysql RDS instance
"""
result = []
conn = pymysql.connect(rds_host, user=name, passwd=password,
db=db_name,connect_timeout=30)
with conn.cursor() as cur:
cur.execute("SELECT * FROM exercise WHERE bid = '1'")
for row in cur:
result.append(list(row))
print ("Data from RDS...")
print (result)
cur.close()
print(json.dumps({'bodyParts':result}))
def lambda_handler(event, context):
save_events(event)
As pointed out in a comment by #John Gordon, you need to return something from your lambda_handler function.
It should be something like:
def lambda_handler(event, context):
save_events(event)
return {
"statusCode": 200,
"result": "Here is my result"
}
Additionally, I don't see any return statement from save_events either.

Categories

Resources