Quickstart: Een Python Durable Functions-app maken

Gebruik Durable Functions, een functie van Azure Functions, om stateful serverloze werkstromen in Python te schrijven. In deze snelstartgids kloont u een voorbeeldtoepassing en voert u deze uit, waarin twee veelvoorkomende orkestratiepatronen worden gedemonstreerd:

  • Functiekoppeling: Roept activiteiten opeenvolgend aan (Tokio → Seattle → Londen).
  • Fan-out/fan-in: roept activiteiten parallel aan in vijf steden en voegt vervolgens de resultaten samen.

Aan het einde hebt u beide orchestraties lokaal draaien met de Durable Task Scheduler-emulator en kunt u hun status bekijken in het dashboard.

  • Kloon en bereid het Hello Cities-voorbeeldproject voor.
  • Stel de Durable Task Scheduler emulator en Azurite in voor lokale ontwikkeling.
  • Voer de functie-app uit en start beide orchestraties.
  • Controleer de orchestratiestatus en uitvoer in het dashboard van Durable Task Scheduler.

Prerequisites

De emulator voor Durable Task Scheduler instellen

De Durable Task Scheduler-emulator biedt een lokale ontwikkelomgeving, zodat u indelingen kunt testen zonder een Azure abonnement. De Functions-host vereist ook Azurite voor lokale opslag.

Start beide containers op:

docker run -d --name dtsemulator -p 8080:8080 -p 8082:8082 \
  mcr.microsoft.com/dts/dts-emulator:latest

docker run -d --name azurite -p 10000:10000 -p 10001:10001 -p 10002:10002 \
  mcr.microsoft.com/azure-storage/azurite

Tip

Zodra de emulator actief is, kunt u het Durable Task Scheduler-dashboard openen op http://localhost:8082 om orchestraties te bewaken.

Het snelstartvoorbeeld uitvoeren

  1. Navigeer naar de voorbeeldmap Hello Cities:

    cd samples/durable-functions/python/hello-cities
    
  2. Maak een virtuele omgeving en installeer afhankelijkheden:

    python -m venv .venv
    .venv\Scripts\activate
    pip install -r requirements.txt
    
  3. Controleer of het local.settings.json bestand de volgende configuratie bevat:

    {
      "IsEncrypted": false,
      "Values": {
        "AzureWebJobsStorage": "UseDevelopmentStorage=true",
        "FUNCTIONS_WORKER_RUNTIME": "python",
        "DURABLE_TASK_SCHEDULER_CONNECTION_STRING": "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None"
      }
    }
    
  4. Start de functie-app:

    func start
    
  5. Start in een aparte terminal de orkestratie van functiechaining:

    $response = Invoke-RestMethod -Method POST -Uri http://localhost:7071/api/StartChaining
    $response
    

    Het antwoord bevat status-URL's voor de orchestratie-instantie. Kopieer de waarde statusQueryGetUri en voer deze uit om het resultaat te controleren:

    Invoke-RestMethod -Uri $response.statusQueryGetUri
    
  6. Start de fan-out/fan-in-orchestratie:

    $response = Invoke-RestMethod -Method POST -Uri http://localhost:7071/api/StartFanOutFanIn
    Invoke-RestMethod -Uri $response.statusQueryGetUri
    

Verwachte uitvoer

De POST-aanvraag retourneert een JSON-antwoord met status-URL's. Voorbeeld:

{
  "id": "<instanceId>",
  "statusQueryGetUri": "http://localhost:7071/runtime/webhooks/durabletask/instances/<instanceId>?code=...",
  "sendEventPostUri": "...",
  "terminatePostUri": "...",
  "purgeHistoryDeleteUri": "..."
}

Wanneer u een query uitvoert op statusQueryGetUri en de runtimeStatus van de orchestratie Completed is, kunt u de resultaten van de begroeting vinden in het veld output. De ketenorkestratie retourneert:

{
  "name": "chaining_orchestration",
  "runtimeStatus": "Completed",
  "output": ["Hello Tokyo!", "Hello Seattle!", "Hello London!"]
}

De fan-out/fan-in-orchestratie retourneert:

{
  "name": "fan_out_fan_in_orchestration",
  "runtimeStatus": "Completed",
  "output": ["Hello Tokyo!", "Hello Seattle!", "Hello London!", "Hello Paris!", "Hello Berlin!"]
}

Tip

Als runtimeStatusRunning of Pending weergeeft, wacht dan even en voer de statusQueryGetUri opnieuw uit.

Open het dashboard van Durable Task Scheduler op http://localhost:8082 om de orchestrationstatus en uitvoeringsgeschiedenis te bekijken.

De code begrijpen

Het voorbeeld maakt gebruik van het Python v2-programmeermodel met decorators, waarbij alle functies in één bestand zijn gedefinieerd (function_app.py).

Activiteitsfunctie

De say_hello activiteit heeft een plaatsnaam en retourneert een begroeting:

@app.activity_trigger(input_name="city")
def say_hello(city: str) -> str:
    """Activity function that returns a greeting for a city."""
    logging.info(f"Saying hello to {city}.")
    return f"Hello {city}!"

Orchestratorfuncties

De chaining orchestrator roept say_hello opeenvolgend aan voor drie steden:

@app.orchestration_trigger(context_name="context")
def chaining_orchestration(context: df.DurableOrchestrationContext):
    """Function chaining orchestration: calls activities sequentially."""
    result1 = yield context.call_activity("say_hello", "Tokyo")
    result2 = yield context.call_activity("say_hello", "Seattle")
    result3 = yield context.call_activity("say_hello", "London")
    return [result1, result2, result3]

De fan-out/fan-in orchestrator plant activiteiten parallel:

@app.orchestration_trigger(context_name="context")
def fan_out_fan_in_orchestration(context: df.DurableOrchestrationContext):
    """Fan-out/Fan-in orchestration: calls activities in parallel."""
    cities = ["Tokyo", "Seattle", "London", "Paris", "Berlin"]

    # Fan-out: schedule all activities in parallel
    parallel_tasks = []
    for city in cities:
        task = context.call_activity("say_hello", city)
        parallel_tasks.append(task)

    # Fan-in: wait for all to complete
    results = yield context.task_all(parallel_tasks)
    return results

Clientfuncties

Door HTTP geactiveerde clientfuncties starten elke orchestratie. Bijvoorbeeld de koppelingsstarter:

@app.route(route="StartChaining", methods=["POST"])
@app.durable_client_input(client_name="client")
async def start_chaining(req: func.HttpRequest, client) -> func.HttpResponse:
    """HTTP trigger to start the function chaining orchestration."""
    instance_id = await client.start_new("chaining_orchestration")
    logging.info(f"Started chaining orchestration with ID = '{instance_id}'.")
    return client.create_check_status_response(req, instance_id)

Configuratie

In het voorbeeld wordt de Durable Task Scheduler-emulator gebruikt als de back-end voor opslag. Dit is geconfigureerd in host.json:

{
  "version": "2.0",
  "logging": {
    "logLevel": {
      "DurableTask.Core": "Warning"
    }
  },
  "extensions": {
    "durableTask": {
      "hubName": "default",
      "storageProvider": {
        "type": "azureManaged",
        "connectionStringName": "DURABLE_TASK_SCHEDULER_CONNECTION_STRING"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

De hulpbronnen opschonen

Stop de containers van de emulator wanneer u klaar bent:

docker stop dtsemulator azurite && docker rm dtsemulator azurite

De Python virtuele omgeving deactiveren:

deactivate

Volgende stappen