Lambda Function to Call Database - python-3.x

I am new to AWS/Lambda/Amazon Connect and trying my way around it. I have the below code to request Information from my dynamoDB table and update the table in case of a new entry. My issue is that the function only seems to run the except part and completely ignores the try. Need to understand why
CODE
import boto3
import json
from boto3.dynamodb.conditions import Key, Attr
def lambda_handler(event, context):
print("Lambda Trigger event: " + json.dumps(event))
try:
phoneNumber = event['Details']['ContactData']['CustomerEndpoint']['Address']
print("Customer Phone Number : " + phoneNumber)
dynamodb = boto3.resource('dynamodb',region_name='ap-southeast-2')
table = dynamodb.Table('data_dip_table')
response = table.get_item(Key={
'phone-number': phoneNumber
})
print("dynamodb response: " + json.dumps(response))
if 'Item' in response:
# TODO: Match Found
print("Phone number match found!")
firstName = response['Item']['first-name']
print("Customer First Name: " + firstName)
welcomeMessage = 'Welcome' + firstName + ' to Our data dip'
print("welcome message :" + welcomeMessage)
return {'welcomeMessage' : welcomeMessage }
else:
print("Phone Number was not Found")
return { 'welcomeMessage' : 'Welcome!' }
except Exception as e:
print("An Error Has Occurred")
print(e)
return {'welcomeMessage' : 'Welcome !'}
My Output is
Response:
{
"welcomeMessage": "Welcome !"
}
Request ID:
"0d9b6bf6-62f8-4385-81f0-f1d36ee489c8"
Function Logs:
START RequestId: 0d9b6bf6-62f8-4385-81f0-f1d36ee489c8 Version: $LATEST
Lambda Trigger event: {}
An Error Has Occurred
'Details'
END RequestId: 0d9b6bf6-62f8-4385-81f0-f1d36ee489c8
I have an entry for my phone number in the DD table but still get an error.Any ideas ??

The event object is empty. Check this line in CloudWatchLogs:
Lambda Trigger event: {}
Your code is definitely not ignoring the try block, however, on the first line of your try block, you have phoneNumber = event['Details']['ContactData']['CustomerEndpoint']['Address'] which automatically fails because your event is empty, therefore redirecting the execution to the except block.
How is this function being triggered? If you are doing it manually from AWS's Console, you will have to create a test event that contains the body that your method expects.

Related

Azure service bus message auto renewal not working as expected

I have a python service which sends and receives message from azure service bus queue. As per my setup the received will take long time to do some precess and finally completing the message.
To tackle this scenario added auto lock renewal with max_lock_renewal_duration=3600 and set message lock duration as 1 minute.
when i check the log for the first time the lock renewal worked fine but for the second time it errored out. But when i printed the error it just logging the received message not the error.
Code:
class AzureMessageQueue(MessageQueue):
async def on_renew_error(renewable, error, _):
print("On renew error -\n renewable: ", renewable,"\n error: ", error,"\n type: ", type(error), "\n message: ", error.message)
if type(error) == MessageAlreadySettled:
logger.warn("Message already settled")
else:
logger.warn("Error renewing lock: %s", error)
def __init__(self, conn_str: str, queue_name: str) -> None:
self.sb_client: ServiceBusClient = ServiceBusClient.from_connection_string(
conn_str=conn_str,
logging_enable=True,
retry_total=10,
retry_backoff_factor=1,
)
self.sender: ServiceBusSender = self.sb_client.get_queue_sender(queue_name)
self.receiver: ServiceBusReceiver = self.sb_client.get_queue_receiver(
queue_name
)
self.renewer: AutoLockRenewer = AutoLockRenewer(
max_lock_renewal_duration=3600, on_lock_renew_failure=self.on_renew_error
)
async def send(self, message: str) -> None:
sb_message = ServiceBusMessage(message)
await self.sender.send_messages(sb_message)
async def process(self, processor) -> AsyncIterator:
async with self.receiver:
async for msg in self.receiver:
self.renewer.register(self.receiver, msg)
message = str(msg)
try:
result = await processor(message)
await self.receiver.complete_message(msg)
yield message, None, result
except Exception as e:
yield message, e, None
Log:
On renew error -
renewable: <api.message_queue.AzureMessageQueue object at 0x7fe34bdaea90>
error: {"message": "test"}
type: <class 'azure.servicebus._common.message.ServiceBusReceivedMessage'>
message: {"message": "test"}
i'm trying to understand what caused the issue?
Im using python azure service bus sdk(azure-servicebus~=7.6.0).
Thanks in advance!

ERROR - Runtime.HandlerNotFound: Handler 'lambda_handler' missing on module 'lambda_function'

My apologies for basic question. I am completely new to AWS as well as Python. I am trying to do sample code but facing a error. I'm trying to read some data from a dynamodb table, but facing error like this in AWS Cloudwatch logs:
"Runtime.HandlerNotFound: Handler 'lambda_handler' missing on module 'lambda_function'".
And Postman is throwing error as
"message": "Internal server error"
The code is:
import boto3
class userProfile:
def __init__(self):
dynamodb = boto3.resource('dynamodb')
self.table = dynamodb.Table('user_data')
def Create_table():
pass
def Read_table(self, event):
response = self.table.get_item(
Key = {
'user_name' : event['user_name']
}
)
if 'Item' in response:
return response['Item']
else:
return {
'statusCode':'404',
'body' : 'User Name ' + 'id ' + 'not found'
}
def Update_tabel():
pass
def lambda_handler(event, context):
if event:
user_Object = userProfile()
if event["tasktype"] == "read":
read_result = user_Object.Read_table(event['data'])
return read_result
else:
return {
'statusCode': '404',
'body': 'Not found'
}

Update Insight Custom field => cannot be cast to java.util.Collection'

I have a strange problem. My script is practically finished.
To understand the script : In Insight, I have all our servers object created automatically.
We use a monitoring called Centreon, this monitoring send an email to the service desk mailbox automatically when a error occur and a ticket is created. I want to add the corresponding object to the corresponding server.
The name of the server is present in the summary of the email;
Example : AFDAOS.xxx.int problem alert
A groovy script check the name of the server, if it found a correspond name (in the FQDN Attribute), the object is affected to the ticket.
All code working until the updating of the ticket, i have a statement where all objects are checked, when i found the good object (string currentobject), i want to update the current issue with this object i have the error :
GroovyInsightException: com.riadalabs.jira.plugins.insight.services.model.ObjectBean cannot be cast to java.util.Collection'
BUT if I replace currentobject by Objects (I suppose it's an array), the ticket is updating with all objects without any error. I understand that I can only update the ticket with an array and not a unique value... I don't found the good way to do it... Thank you for your help.
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.fields.CustomField
import com.riadalabs.jira.plugins.insight.services.model.CommentBean;
import com.atlassian.jira.issue.MutableIssue
import com.atlassian.jira.event.type.EventDispatchOption
import com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade
import com.riadalabs.jira.plugins.insight.services.model.ObjectAttributeBean
import com.riadalabs.jira.plugins.insight.services.model.ObjectBean
import groovy.transform.ToString
Class objectFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.ObjectFacade");
def objectFacade = ComponentAccessor.getOSGiComponentInstanceOfType(objectFacadeClass);
//CustomField jiraCustomField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(12124);
CustomField insightCF = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(12124);
Class iqlFacadeClass = ComponentAccessor.getPluginAccessor().getClassLoader().findClass("com.riadalabs.jira.plugins.insight.channel.external.api.facade.IQLFacade");
def iqlFacade = ComponentAccessor.getOSGiComponentInstanceOfType(iqlFacadeClass);
def objects = iqlFacade.findObjectsByIQLAndSchema(10,"objectTypeId = 2443");
//def test = "AF-172738"
//def ObjectInsightBean = objectFacade.loadObjectBean(test)
//log.warn("ObjectInsightBean " + ObjectInsightBean)
def n = 0
(objects).each {
CurrentObject = objects[n]
def fqdnvalue = objectFacade.loadObjectAttributeBean(CurrentObject.getId(),47464).getObjectAttributeValueBeans()[0]; //Load Attribute Value
def fqdn_string = fqdnvalue.toString()
def fqdn_string_split = fqdn_string.split("\\(");
def fqdn_string_split_1 = fqdn_string_split[1]
def fqdn_string_split_2 = fqdn_string_split_1.substring(0, fqdn_string_split_1.length() - 2);
result = (issue.getSummary().contains(fqdn_string_split_2)) // if the value fqdn_string_split_2 present in the summary => result = true
if (result==true){
log.info("Statement " + "True" + CurrentObject);
MutableIssue mi = (MutableIssue) issue;
mi.setCustomFieldValue(insightCF, CurrentObject); // => Work if i replace CurrentObject by objects
ComponentAccessor.getIssueManager().updateIssue(currentUser, mi, EventDispatchOption.DO_NOT_DISPATCH, false); // Error GroovyInsightException: com.riadalabs.jira.plugins.insight.services.model.ObjectBean cannot be cast to java.util.Collection'
}
log.info("fqdn_string_split_2 " + fqdn_string_split_2)
log.info("Result " + result)
n ++
return result;
}
Solved by converting the string into List:
if (result==true){
//log.info("Statement " + "True" + CurrentObject);
MutableIssue mi = (MutableIssue) issue;
def CurrentObject_list = [CurrentObject];
log.info("List " + CurrentObject_list);
mi.setCustomFieldValue(insightCF, CurrentObject_list); // => Work if i replace CurrentObject by objects
ComponentAccessor.getIssueManager().updateIssue(currentUser, mi, EventDispatchOption.DO_NOT_DISPATCH, false); // Error GroovyInsightException: com.riadalabs.jira.plugins.insight.services.model.ObjectBean cannot be cast to java.util.Collection'
}
//log.info("fqdn_string_split_2 " + fqdn_string_split_2)
//log.info("Result " + result)
n ++
return result;

Azure Functions HTTP Trigger : How to return exception from python worker log to the API caller

I'm new to Azure functions
Wished to know how to return exception from python worker log to the API caller .
In a HTTP Trigger with COSMOS DB binding , on firing an insert call to the binding , if data already exists , it fails with
"System.Private.CoreLib: Exception while executing function: Functions.insertEntityData. Microsoft.Azure.DocumentDB.Core: Entity with the specified id already exists in the system."
How can this message be sent back to the end user ? It is not getting captured anywhere.
def main(req: func.HttpRequest, cosmosdata: func.Out[func.Document]) -> func.HttpResponse:
try:
message = ""
logging.info('Python HTTP trigger function processed a request.')
entity_name = req.route_params['entity']
status_code = 500
payload = req.get_json()
if payload:
try:
logging.info(payload)
resultant = cosmosdata.set(func.Document.from_dict(payload))
logging.info(resultant)
status_code = 200
message = "Insert Successful to %s" % (entity_name)
except Exception as e:
return func.HttpResponse(str(e), status_code=500)
else:
status_code = 400
message = "Please pass data in the POST Request"
except Exception as e:
return func.HttpResponse(str(e), status_code=500)
return func.HttpResponse(message, status_code=500)
The try / catch block is not working because you're using an Output binding to Cosmos Db, which is the one that is failing. However, it also looks weird to me because by default it performs and Upsert operation.
I believe the problem relates to your partition Key defined in the function.json file.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-cosmosdb-v2#input---python-examples

addAssertion() not recognizing string value of "Contains" type

I have a groovy script that I've added code to to check if a value exists in an XML response I'm getting within SoapUI. I've been dealing with this for a few days and could use some help.
Here is the code:
import com.eviware.soapui.support.XmlHolder
import com.eviware.soapui.impl.wsdl.teststeps.registry.RestRequestStepFactory
// read your request template
def requestFile = new File("C:/XMLRequestScript/file.xml");
// parse it as xml
def requestXml = new XmlHolder(requestFile.text)
// get the current testCase to add testSteps later
def tc = testRunner.testCase;
// get the testStep as template to create the other requests
def tsTemplate = tc.getTestStepByName("Template");
// loop to create # of testSteps for each application
for(int i = 1; i < 3; i++) {
// xpath expression to get applicationNumber attribute in root node
def xpathNodeAttr = "/*/#ApplicationNumber";
// get the root node attribute applicationNumber throught an XPATH
int appId = Integer.parseInt(requestXml.getNodeValue(xpathNodeAttr));
// add 1 to appId
appId++;
// set the value again in the attribute
requestXml.setNodeValue(xpathNodeAttr,appId);
// create next testStepName for new Application
def testStepName = "TestStep_ApplicationNumber_" + String.valueOf(appId)
log.info testStepName;
log.info testStepName.getClass().getName()
log.info tc.getClass().getName()
// create a new testStepConfig
def testStepFactory = new RestRequestStepFactory();
def testStepConfig = testStepFactory.createConfig( tsTemplate.getTestRequest(), testStepName )
// add the new testStep to TestCase
def newTestStep = tc.insertTestStep( testStepConfig, -1 )
// set the request
newTestStep.getTestRequest().setRequestContent(requestXml.getXml())
// add Assertions here
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
if (assertion.contains("Champion5")) {
newTestStep.addAssertion("Champion5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
if (assertion.contains("Challenger5")) {
newTestStep.addAssertion("Challenger5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
// execute the request
newTestStep.run(testRunner, context)
}
In the section above called "// add Assertions here", the line of code that I'm having a problem with is:
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
The error states:
Thu Sep 18 14:27:57 CDT 2014:ERROR:An error occurred [Cannot invoke method addAssertion() on null object], see error log for details
My understanding is that I have to pass an Assertion Type that is contained in the SoapUI GUI and just put it in as a string value in order to check if the values that I'm checking are asserted.
Any suggestions/direction would be appreciated. I have no idea what I'm doing wrong. Thanks.
I think the problem is your are calling the function tc.getTestStepByName(String name) with a wrong name, because the newTestStep.toString() doesn't return the Test step name instead it returns the class name (it really returns 'classname' + '#' + 'Integer.toHexString(hashCode())' if it's not override it, see Object.toString()) .
Anyway what you want is to add an assertion for a test step which is just created so add the assertion directly to it instead to find it by name, use:
def assertion = newTestStep.addAssertion("Contains")
instead of:
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
The second problem you have is that you're using the assertion incorrectly. The assertion object in your case is an instance of SimpleContainsAssertion and contains() method doesn't exist in this class, to set the string to check in contains assert use setToken() method, I think that you need this to add the two assertions:
def assertion = newTestStep.addAssertion("Contains")
// add token to check
assertion.setToken("Champion5")
// change assert name in order to avoid the popup
// when we create the second one.
assertion.setName("CONTAINS 1")
// create a second assertion
assertion = newTestStep.addAssertion("Contains")
assertion.setToken("Challenger5")
assertion.setName("CONTAINS 2")
instead of :
// add Assertions here
def assertion = tc.getTestStepByName(newTestStep.toString()).addAssertion("Contains")
if (assertion.contains("Champion5")) {
newTestStep.addAssertion("Champion5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
if (assertion.contains("Challenger5")) {
newTestStep.addAssertion("Challenger5")
log.info("REST response assertion created into: " + newTestStep)
} else {
log.info("REST response assertion not found in " + newTestStep)
}
This code will result creating this two asserts, one named "CONTAINS 1" and check that response contains the string "Champion5", and a second one named "CONTAINS 2" and check that response contains the string "Challenge5".
Hope this helps,

Resources