search
HomeBackend DevelopmentPython TutorialAzure Functions with Python: Triggers

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")

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.')

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")

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")

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.')

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")

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")

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
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
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.