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()))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.