Cloud Function Deployment failure When Using Wildcard in Trigger - python

So, basically the same issue as in this SO post except I'm using Python and the accepted answer didn't help.
Using the provided template in the Console UI:
def hello_firestore(event, context):
"""Triggered by a change to a Firestore document.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
resource_string = context.resource
# print out the resource string that triggered the function
print(f"Function triggered by change to: {resource_string}.")
# now print out the entire event object
print(str(event))
with a wildcard in the trigger path:
'emails/{wildcard}'
I'm getting the below error:
Deployment failure: Failed to configure trigger
providers/cloud.firestore/eventTypes/document.create#firestore.googleapis.com
(gcf.us-central1.presignups-counter)
Similarly as in the referenced question, the error clears when removing the wildcard from the trigger resource:
'emails/wildcard'
EDIT: here is a screenshot of the Function Details:

I was able to deploy the cloud function using : emails/{wildcard} and not 'emails/{wildcard}'.
The reason for that is that when the document path is added in the UI then it should be without the single quotes. When it's in the code, then it should be in single quotes. More information here

Related

Call Azure Function (Python) from Data Factory: Response Content is not a valid JObject

I'm trying to call a python httptriggered Azure Function from Azure Data Factory. It is the default generated code by Visual Studio code (only added comments). First testing it in Azure Functions in the Azure portal and that works.
Then in ADF via the Azure Function Activity (followed instrunctions)
But it keeps returning errors: 3603 - Response Content is not a valid JObject
As per https://learn.microsoft.com/azure/data-factory/control-flow-azure-function-activity, "The return type of the Azure function has to be a valid JObject. (Keep in mind that JArray is not a JObject.) Any return type other than JObject fails and raises the user error Response Content is not a valid JObject". In other words, the Azure Function needs to return JSON as its response rather than the plain string that the generated code returns.

Failing to invoke Google Cloud Function with Google Cloud Scheduler

I have created a Google Cloud Function using Python 3.7. Testing the function itself, it behaves as expected. I have set the trigger of the function to be a topic called "Scheduled".
The code itself runs a series of API calls, when tested manually from the UI works exactly as expected.
Output when running a manual test.
The original source code requires no arguments for the main function inside the script, however I realized the Cloud Function passes 2 to it anyway, so I have added them with no actual use:
def main(event, data):
print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
getNotifs = getNotifications()
if getNotifs["hasData"] == True:
print("Found notifications, posting to Telegram.")
notifsParsed = parseNotifications(getNotifs["data"])
telegramCall = telegramPost(
{"text": str(notifsParsed), "chat_id": ChatId, "parse_mode": "HTML"})
print(telegramCall)
elif getNotifs["hasData"] == False:
print(getNotifs["error"])
print("================================")
Now, I have created a new Cloud Scheduler job where the target is "pub/sub" and the topic is also "Scheduled". Nowhere could I find a use for the required 'payload' field, and the Scheduler guide by Google only fills in a random value, 'hello' without quotes or something like it, so I filled in 'hi'.
Running the job I am repeatedly met with a failure, and this log:
status: "INVALID_ARGUMENT"
targetType: "PUB_SUB".
I have tried changing the payload to "hi" (with quotes), editing the main PY function to accept one more argument, both seem entirely unrelated. What am I missing?
Only issue was a mistype of the topic defined in the scheduler job, it's free text and not a selection of existing topics or anything.

How to integrate Lambda, Alexa, and my code (Python - Tweepy)?

I am trying to tweet something by talking to Alexa. I want to put my code on AWS Lambda, and trigger the function by Alexa.
I already have a Python code that can tweet certain string successfully. And I also managed to create a zip file and deploy it on Lambda (code depends on the "tweepy" package). However, I could not get to trigger the function by Alexa, I understand that I need to use handlers and ASK-SDK (Alexa Service Kit), but I am kind of lost at this stage. Could anyone please give me an idea about how the handlers work and help me see the big picture?
Alexa ASK_SDK Psuedo Code:
This is pseudo code of the new ASK_SDK, which is the predecessor to the ALEXA_SDK.
Also note I work in NodeJS but the structure is likely the same
Outer Function with Call Back - Lambda Function Handler
CanHandle Function
Contains logic to determine if this handler is the right handler. The HandlerInput variable contains the request data so you can check and see if the intent == "A specific intent" then return true. Else return false. Or you can go way more specific. (Firing handlers by intent is pretty basic. you can take it a step further and fire handlers based on Intent and State.
Handle Function
Which ever "canHandle" function returns true this is the code that will be run. The handler has a few functions it can perform. It can read the session attributes, change the session attributes based on the intent that was called, formulate a string response, read and write to a more persistant attribute store like dynamodb and create and fire an alexa response.
The handerInput contains everything you'll need. I'd highly recommend running your test code in Pycharm with the debugger and then examining the handlerInput variable.
The response builder is also very important and is what allows you to add speech, follow up prompts, cards, elicit slot values etc.
handler_input.response_builder
Example to Examine
https://github.com/alexa/skill-sample-python-helloworld-classes/blob/master/lambda/py/hello_world.py
class HelloWorldIntentHandler(AbstractRequestHandler):
"""Handler for Hello World Intent."""
def can_handle(self, handler_input):
# type: (HandlerInput) -> bool
return ask_utils.is_intent_name("HelloWorldIntent")(handler_input)
def handle(self, handler_input):
# type: (HandlerInput) -> Response
speak_output = "Hello Python World from Classes!"
return (
handler_input.response_builder
.speak(speak_output)
# .ask("add a reprompt if you want to keep the session open for the user to respond")
.response
)
For your question about capturing user's input for tweeting, use AMAZON.SearchQuery slot type. You may run into limitations about how much text can be collected and the quality of the capture but SearchQuery slot is the place to start.

How to write a hello world example in AWS Lambda using Python 2.7?

I am utterly confused by the docs in AWS.
What I tried
Signed up an AWS account using the region us-west-2
Created a Lambda function called helloworld
Created a handler called hello_world inside.
Selected Actions > Configure Test Event > Selected Common > Hello World
Press Test and I get the following error messages:
The area below shows the result returned by your function execution.
{
"errorMessage": "Syntax error in module 'helloworld'"
}
and
START RequestId: f71b8c46-ecc8-11e5-91b6-c55c85fd12cb Version: $LATEST
Syntax error in module 'helloworld': invalid syntax (helloworld.py, line 1)
END RequestId: f71b8c46-ecc8-11e5-91b6-c55c85fd12cb
REPORT RequestId: f71b8c46-ecc8-11e5-91b6-c55c85fd12cb Duration: 0.29 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 10 MB
What I wanted
I just want to get a successful execution of a python hello world, so I know where I am supposed to observe the output and how to run the script.
Updates
I have changed the code to
def print_something(entry, second_entry):
print str(entry)
print str(second_entry)
return str(second_entry)
And it is executed properly.
This is what I saw:
START RequestId: 33bf2a83-ecda-11e5-bdcd-2de843a18bed Version: $LATEST
{u'key3': u'value3', u'key2': u'value2', u'key1': u'value1'}
<__main__.LambdaContext object at 0x7f66d1848990>
END RequestId: 33bf2a83-ecda-11e5-bdcd-2de843a18bed
What on earth is that LamdaContext object that appears as the second param?
Two issues:
the python function was wrongly defined
the main handler for Lambda requires 2 arguments
Answer:
def hello_world(event_data, lambda_config):
print "hello world"
For more information on the arguments for the main handler, read http://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html
Excerpt:
Use the following general syntax structure when creating a handler function in Python.
def handler_name(event, context):
...
return some_value
In the syntax, note the following:
event – AWS Lambda uses this parameter to pass in event data to the handler. This parameter is usually of the Python dict type. It can also be list, str, int, float, or NoneType type.
context – AWS Lambda uses this parameter to provide runtime information to your handler. This parameter is of the LambdaContext type.
Optionally, the handler can return a value. What happens to the returned value depends on the invocation type you use when invoking the Lambda function:
If you use the RequestResponse invocation type (synchronous execution), AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON). For example, AWS Lambda console uses the RequestResponse invocation type, so when you test invoke the function using the console, the console will display the returned value.
If the handler does not return anything, AWS Lambda returns null.
If you use the Event invocation type (asynchronous execution), the value is discarded.
change your python syntax into
def event_handler(event,context):
message = "hello{0}".format(event['world'])
return mesaage
here event always like dictionary type object
and Context is lambda context
For python function:
def helloworld():
print "helloworld"
then, in the configuration you should use "helloworld" as lambda handler.

Specify post-installation script when creating an instance in OpenStack [python-novaclient]

I have a working python program which is able to create instances on OpenStack thanks to the python-novaclient library.
Now I'd like to give a post-installation script at the creation time. I looked at the documentation of the Servers.create() method but it doesn't seem to be implemented.
Did anyone faced this problem?
EDIT
In Horizon, when we create an instance, there is this information next to the textarea for the post-installation script:
The "Customisation Script" field is analogous to "User Data" in other systems.
Does it mean userdata is the parameter I need?
userdata – user data to pass to be exposed by the metadata server this can be a file type object as well or a string.
Indeed the solution is on userdata
Here's the Python code I wrote to solve my problem:
## Return the new created instance
# #param name Name of the instance to create in a String format
# #param image OpenStack image to deploy on the virtual machine
# #param flavor OpenStack flavor to use for the virtual machine
# #param keypair Name of the keypair to copy on the instance
# #param sec_groups List of security groups to link to the instance
def create_instance(self,name,image,flavor,keypair=None,sec_groups=None):
instance = self.client.servers.create(
name=name,
image=image,
flavor=flavor,
key_name=keypair,
security_groups=sec_groups,
userdata="#!/bin/bash \n echo 'AMAZING TEST' > /root/test"
)
return instance
Try enabling config drive. The user data can be sent to VM via config drive.

Categories

Resources