Search code examples
python-3.xazure-functionsazure-eventhubazure-functions-core-toolsazure-function-async

How send data to the event while using timer trigger azure function v2 in python


I'm trying to send data every 10 seconds to an Event Hub using the Azure Functions v2. Here my code for function.json

    {
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "mytimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "*/10 * * * * *"
    },
    {
      "type": "eventHub",
      "name": "$return",
      "eventHubName": "sqlserverstreaming",
      "connection": "amqps://desrealtimestreaming.servicebus.windows.net",
      "direction": "out"
  }
  ]
}

Here my code for init.py

    import datetime
import logging
import azure.functions as func


def main(mytimer: func.TimerRequest) -> None:
    utc_timestamp = datetime.datetime.utcnow().replace(
        tzinfo=datetime.timezone.utc).isoformat()
    print('saran')
    return 'Message created at: {}'.format(utc_timestamp)
    # if mytimer.past_due:
    #     logging.info('The timer is past due!')
    # logging.info('Python timer trigger function ran at %s', utc_timestamp)

And I'm getting the following error.

 Executed 'Functions.TimerTriggerFUnction' (Failed, Id=fa924331-418f-427f-b672-f525c3ee6b61)
[07-08-2019 09:03:40] System.Private.CoreLib: Exception while executing function: Functions.TimerTriggerFUnction. System.Private.CoreLib: Result: Failure
Exception: FunctionLoadError: cannot load the TimerTriggerFUnction function: Python return annotation "NoneType" does not match binding type "eventHub"
Stack:   File "C:\Users\SivaSakthiVelan\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\deps\azure\functions_worker\dispatcher.py", line 240, in _handle__function_load_request
    function_id, func, func_request.metadata)
  File "C:\Users\SivaSakthiVelan\AppData\Roaming\npm\node_modules\azure-functions-core-tools\bin\workers\python\deps\azure\functions_worker\functions.py", line 241, in add_function
    f'Python return annotation "{return_pytype.__name__}" '

Solution

  • Change your return type from None to str

    def main(mytimer: func.TimerRequest) -> str:
    

    See here for complete example: https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs#output---python-example

    Also, your connection property should have the name of the app setting that contains the connection string, not the connection string itself (see also in the example), so like this:

      "type": "eventHub",
      "name": "$return",
      "eventHubName": "sqlserverstreaming",
      "connection": "MyConnStringAppSetting",
      "direction": "out"
    

    And then create an app setting named MyConnStringAppSetting and put your full connection string in there.