Home Backend Development Python Tutorial Azure Functions with Python: Triggers

Azure Functions with Python: Triggers

Jan 03, 2025 am 02:57 AM

Azure Functions with Python: Triggers

Python developers can use Azure Functions to create lightweight, scalable, and efficient serverless applications. In this post, we will focus on triggers.

What Are Triggers in Azure Functions?

Triggers are the foundation of Azure Functions. They determine how a function is invoked. Each function must have exactly one trigger, and the trigger type dictates the data payload available to the function. Azure supports various triggers, including:

1​. HTTP Trigger

  • Allows functions to be invoked via HTTP requests.
  • Useful for building APIs or responding to webhooks.
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.route(route="http_trigger", auth_level=func.AuthLevel.ANONYMOUS)
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    return func.HttpResponse("Hello world from HTTP trigger")
Copy after login
Copy after login
Copy after login

Parameters:

  • route: Specifies the URL path to which the HTTP trigger will respond. In this case, the function is accessible at /api/http_trigger.
  • auth_level: Determines the authentication level for the function. Options include:
    • ANONYMOUS: No authentication required.
    • FUNCTION: Requires a function-specific key.
    • ADMIN: Requires an admin-level key.

2​. Timer Trigger

  • Executes functions based on a schedule.
  • Cron expressions are used for scheduling.
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.timer_trigger(schedule="0 */5 * * * *", arg_name="myTimer", run_on_startup=False, use_monitor=False)
def timer_trigger(myTimer: func.TimerRequest) -> None:

    if myTimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function executed.')
Copy after login
Copy after login

Parameters:

  • schedule: Defines the schedule using a CRON expression. Here, 0 */5 * * * * specifies the function runs every 5 minutes starting at the 0th second.
  • arg_name: The name of the argument passed to the function, representing the TimerRequest object.
  • run_on_startup: If set to True, the function executes immediately when the app starts. Default is False.
  • use_monitor: Determines if Azure should monitor for missed schedule executions. If True, Azure ensures missed executions are retried. Default is True. In this example, it is set to False.

3​. Blob Trigger

  • Responds to changes in Azure Blob Storage (e.g., file uploads).
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.blob_trigger(arg_name="myblob", path="blobname", connection="BlobStorageConnectionString")
def BlobTrigger(myblob: func.InputStream):
    logging.info(f"Python blob trigger function processed blob"
                f"Name: {myblob.name}"
                f"Blob Size: {myblob.length} bytes")
Copy after login
Copy after login

Parameters:

  • arg_name: Specifies the name of the argument in the function that represents the blob data. Here it is myblob.
  • path: The path in the Blob Storage container that the function listens to. In this example, it is blobname.
  • connection: Refers to the name of the application setting containing the connection string for the Blob Storage account. Here it is BlobStorageConnectionString.

4​. Queue Trigger

  • Triggered by messages added to Azure Storage Queues.
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.route(route="http_trigger", auth_level=func.AuthLevel.ANONYMOUS)
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    return func.HttpResponse("Hello world from HTTP trigger")
Copy after login
Copy after login
Copy after login

Parameters:

  • arg_name: Specifies the name of the argument that represents the queue message in the function. Here, it is azqueue.
  • queue_name: The name of the Azure Storage Queue that the function listens to. In this case, it is queuename.
  • connection: Refers to the application setting containing the connection string for the Azure Storage Queue. Here, it is QueueConnectionString.

5​. EventHub Trigger

  • Triggered by events sent to an Azure Event Hub.
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.timer_trigger(schedule="0 */5 * * * *", arg_name="myTimer", run_on_startup=False, use_monitor=False)
def timer_trigger(myTimer: func.TimerRequest) -> None:

    if myTimer.past_due:
        logging.info('The timer is past due!')

    logging.info('Python timer trigger function executed.')
Copy after login
Copy after login

Parameters:

  • arg_name: This specifies the name of the parameter that will receive the event data in your function. In this case, azeventhub will be the variable representing the incoming EventHubEvent.
  • event_hub_name: This denotes the name of the Event Hub that the function is listening to. Replace eventhubname with the actual name of your Event Hub.
  • connection: This refers to the name of the application setting that contains the connection string for the Event Hub. Ensure that your Azure Function App's settings include an entry named EventHubConnectionString with the appropriate connection string value.

6​. ServiceBus Queue Trigger

  • Triggered by messages added to an Azure Service Bus queue.
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.blob_trigger(arg_name="myblob", path="blobname", connection="BlobStorageConnectionString")
def BlobTrigger(myblob: func.InputStream):
    logging.info(f"Python blob trigger function processed blob"
                f"Name: {myblob.name}"
                f"Blob Size: {myblob.length} bytes")
Copy after login
Copy after login

Parameters:

  • arg_name: This specifies the name of the parameter that will receive the message data in your function. In this case, azservicebus will be the variable representing the incoming ServiceBusMessage.
  • queue_name: This denotes the name of the Service Bus queue that the function is listening to. Replace servicebusqueuename with the actual name of your Service Bus queue.
  • connection: This refers to the name of the application setting that contains the connection string for the Service Bus. Ensure that your Azure Function App's settings include an entry named ServiceBusConnectionString with the appropriate connection string value.

7​. ServiceBus Topic Trigger

  • Triggered by messages published to an Azure Service Bus topic.
  • Example:
import azure.functions as func
import datetime
import json
import logging

app = func.FunctionApp()

@app.route(route="http_trigger", auth_level=func.AuthLevel.ANONYMOUS)
def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    return func.HttpResponse("Hello world from HTTP trigger")
Copy after login
Copy after login
Copy after login

Parameters:

  • arg_name: Specifies the name of the argument that represents the Service Bus message in the function. Here, it is azservicebus.
  • subscription_name: The name of the Service Bus subscription that the trigger listens to.
  • topic_name: The name of the Service Bus topic that the trigger listens to. In this example, it is servicebustopicname.
  • connection: Refers to the application setting containing the connection string for the Azure Service Bus namespace. Here, it is ServiceBusConnectionString.

Other Triggers

  • Cosmos DB Trigger: Responds to changes (inserts and updates) in an Azure Cosmos DB database by utilizing the change feed mechanism.
  • Dapr Publish Output Binding: Allows functions to publish messages to a Dapr topic during execution, facilitating communication between microservices.
  • Dapr Service Invocation Trigger: Enables functions to be invoked directly by other Dapr-enabled services, supporting service-to-service communication.
  • Dapr Topic Trigger: Executes functions in response to messages published to a specific topic via Dapr's publish-subscribe messaging pattern.
  • Event Grid Trigger: Activates functions when events are sent to an Azure Event Grid topic, allowing for reactive event-driven architectures.

The above is the detailed content of Azure Functions with Python: Triggers. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles