GoogleCloudPlatform / functions-framework-python

FaaS (Function as a service) framework for writing portable Python functions
https://pypi.org/p/functions-framework/
Apache License 2.0
869 stars 118 forks source link

Add example on how to send an event as a client in cloud_run_event #83

Open origliante opened 4 years ago

origliante commented 4 years ago

As in the title, I searched like a crazy and found nothing, an example would be great

di commented 4 years ago

Thanks for the issue. There are some examples in https://github.com/GoogleCloudPlatform/functions-framework-python/issues/23 but ultimately this is blocked on that issue -- the "correct" way would be with the emulator.

origliante commented 4 years ago

You're welcome, thanks for pointing me there, I'm leaving a quick example here for people stumbling upon the issue If you are running:

functions-framework --signature-type=event

This is the way to send an event to the server: $ curl -d '{"data": {"hi": "there"}}' -X POST -H "Content-Type: application/json" http://localhost:8080

MadJlzz commented 3 years ago

Indeed, it's missing documentation on how to call a function when the type is not http. It's quite straightforward though. After some experiments, with a payload that looks like (for a function of type event):

{
    "eventId": "test",
    "timestamp": "2018-04-09T07:56:12.975Z",
    "eventType": "google.pubsub.topic.publish",
    "resource": "my-app",
    "data": {
        "data": "dGhpcyBpcyBkYXRhIG5vb2I=",
        "attributes": {
            "app": "my-app",
            "version": "1.0.0"
        }
  }
}

it returns

{'data': 'dGhpcyBpcyBkYXRhIG5vb2I=', 'attributes': {'app': 'my-app', 'version': '1.0.0'}}
{event_id: test, timestamp: 2018-04-09T07:56:12.975Z, event_type: google.pubsub.topic.publish, resource: my-app}

by doing simply print(event) and print(context)

with a function runned with: functions-framework --target=<name_of_function_to_run> --signature-type=event

Please note that I may have found mismatch with the documentation here.

For example, you have to pass eventId and not event_id for the param to be correctly passed.

Hope this helps and available for PR if needed 😃

grayside commented 3 years ago

Perhaps linking to https://cloud.google.com/functions/docs/running/calling#background_functions would be useful?