Search code examples
azure-functionsazure-eventhub

How to use Azure function imperative output bindings for the eventHub in a python function?


I am trying to setup an azure function to receive messages from EventHub "A", then send messages to one of eventHub "B" or C depending on the input message using function bindings.

Azure functions supports both trigger and output bindings for the EventHub, however, i can't figure out how to setup imperative output bindings properly.

Here are my function.json and python function code so far, inspired by the docs:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "event",
      "type": "eventHubTrigger",
      "direction": "in",
      "eventHubName": "A",
      "consumerGroup": "myConsumerGroup",
      "connection": "aConnectionString"
    },
    {
      "type": "eventHub",
      "name": "B",
      "eventHubName": "B",
      "connection": "bConnectionString",
      "direction": "out"
    },
    {
      "type": "eventHub",
      "name": "C",
      "eventHubname": "C",
      "connection": "cConnectionString",
      "direction": "out"
    }
  ]
}
import logging
import azure.functions as func

def main(event: func.EventHubEvent, B: func.Out, C: func.Out):
  logging.info(f'########################################')
  logging.info(f'Function triggered to process a message:')
  logging.info(f'  EnqueuedTimeUtc = {event.enqueued_time}')
  logging.info(f'  SequenceNumber = {event.sequence_number}')
  logging.info(f'  Offset = {event.offset}')
  logging.info(f'----------------------------------------')
  logging.info(f'  Metadata: ')
  for key in event.metadata:
    logging.info(f'    key {key} = {event.metadata[key]}')
  logging.info(f'  Body = {event.get_body().decode()}')
  logging.info(f'----------------------------------------')
  logging.info(f'B={B}')
  logging.info(f'C={C}')
  logging.info(f'########################################')

With the output bindings and func.Out typed params in the function, the azure function doesn't trigger. Without, it does.

Any help would be greatly appreciated.


Solution

  • I figured it out using the Azurite vscode extension: there were several issues:

    • the output binding name for B had an underscore in it. that makes the name invalid.
    • func.Out is a generic type, and the type needs to be annotated: eg: func.Out[str]