Azure Functions Documentation

Python Queue Trigger Binding

The Azure Queue Storage trigger for Azure Functions allows you to run a function in response to new messages being added to an Azure Queue. This binding is useful for processing messages asynchronously, decoupling services, and handling background tasks.

Prerequisites

Configuration

The queue trigger binding is configured in your function's function.json file. The following is an example configuration:

            
{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "myqueue-items",
      "connection": "AzureWebJobsStorage"
    }
  ]
}
            
        

Binding Properties

Property Description Required
name The name of the variable that represents the message in your function code. Yes
type Must be set to queueTrigger. Yes
direction Must be set to in for a trigger. Yes
queueName The name of the queue to monitor. Yes
connection The name of an app setting that contains your Azure Storage connection string. If not specified, the default AzureWebJobsStorage app setting is used. No

Python Function Code

Your Python function will receive the queue message as an argument. The type of the argument depends on the message content. For simple string messages, it will be a string. For JSON messages, it can be deserialized into a Python dictionary or object.

            
import logging
import azure.functions as func

def main(msg: func.QueueMessage) -> None:
    logging.info('Python queue trigger function processed a queue item.')

    message_body = msg.get_body().decode('utf-8')
    logging.info(f"Received message: {message_body}")

    # Example: Process JSON message
    try:
        message_data = msg.get_json()
        logging.info(f"Parsed JSON: {message_data}")
        # Do something with message_data
    except ValueError:
        logging.warning("Message is not valid JSON.")

    # Example: Access message metadata
    logging.info(f"Message ID: {msg.id}")
    logging.info(f"Insertion Time: {msg.insertion_time}")
    logging.info(f"Expiration Time: {msg.expiration_time}")
    logging.info(f"Dequeue Count: {msg.dequeue_count}")
            
        

Message Handling

Important: If your function execution fails after processing a message, the message will be re-processed by default on subsequent attempts, up to the maximum number of retries defined by the queue. Be mindful of idempotency in your function logic.

Error Handling and Retries

Azure Functions automatically handles retries for queue messages. If your function throws an unhandled exception, the message will be returned to the queue for processing later. You can configure retry behavior at the queue level in Azure Storage.

Monitoring

You can monitor your queue trigger function's activity using Azure Application Insights, which provides detailed logs, metrics, and performance data.

Related Topics